Still just learning PHP so sorry if this is stupid!! I have a function that loops through a mysql adjacency table. I would like to return this as an array. It seems fine, in that if when I return in the function I do print_r($path); where $path is the array inside the function, the array is printed as I want it.
The problem is I cannot see why I cannot access it via
$patharray = functioncalled($vars);
I have tried using return $path; and also just print_r
in the array, but it keeps returning NULL
.
function getParPath($mysqli, $showpar, $path) {
// Get Parent Path
$query ="select loc_id, loc_name, loc_parent from locations where loc_id = ? LIMIT 0,1";
if ($stmt = mysqli_prepare($mysqli, $query)) {
/* pass parameters to query */
mysqli_stmt_bind_param($stmt, "s", $showpar);
/* run the query on the database */
mysqli_stmt_execute($stmt);
/* store result */
mysqli_stmt_store_result($stmt);
/* assign variable for each column to store results in */
mysqli_stmt_bind_result($stmt, $loc_id, $loc_name, $loc_parent);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
$path[] = $loc_name;
if ($loc_parent !='0'){
getParPath($mysqli, $loc_parent, $path);
}
if ($loc_parent =='0'){
$path = array_reverse($path);
return $path; // uncommented per answers below.
//print_r($path); //commented out per answers below.
}
}
}
}
$patharray = getParPath($mysqli, $showcld, $path);
//print_r(getParPath($mysqli, $showcld, $path)); // removed per answers below
var_dump($patharray); //removed echo per answers below
exit;
Which returns:
Array
(
[0] => BuildingA
[1] => FloorA
[2] => RoomA
)
Array
(
[0] => BuildingA
[1] => FloorA
[2] => RoomA
)
NULL
So as you can see from the last line there, the array $patharray
I set to the function call is NULL
. And that if I try to print_r
inside the function, an array is printed, and if I try to print_r
the function directly, it returns an array. But not into an object I can use.