Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

PHP Array in a function

11:59 am on Nov 21, 2012 (gmt 0)


I'm trying to create a function that returns an array of data from a MySQL database but am having some trouble, I.E it isn't working.

I can get the array to work outside of the function but once I put the code into a function, it stops working.

Working array:

$sqlx = "SELECT vehicle_id FROM vehicles WHERE vehicle_diary=1";
$resultx = mysql_query($sqlx);
while ($rowx = mysql_fetch_row($resultx))
$result_array[] = $rowx[0];

This returns - Array ( [0] => 1 [1] => 3 )

Not working function:

function diary_vehicle_select() {
$sqlx = "SELECT vehicle_id FROM vehicles WHERE vehicle_diary=1";
$resultx = mysql_query($sqlx);
$result_array = array();
while ($rowx = mysql_fetch_row($resultx))
$result_array[] = $rowx[0];
return $result_array;

This returns - Array

I have no doubt this is obvious to someone pretty much straight away. I just can't solve it myself. Thanks
1:16 am on Nov 22, 2012 (gmt 0)

10+ Year Member

I don't see anything wrong in the function.

Can you post the code you used to call the function and display the result?

Is it possible that you accidently used "print($result_array)" instead of "print_r($result_array)" when checking the return from the function?

-- Roger
2:45 am on Nov 22, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

What exactly returns "Array". If you do the following, what result do you get?

$newArr = diary_vehicle_select();
9:36 am on Nov 22, 2012 (gmt 0)

I was using echo diary_vehicle_select(); which gave me the result Array.

If I use:

$newArr = diary_vehicle_select();

Then this returns the array correctly, thank you.
11:25 am on Dec 7, 2012 (gmt 0)

array_values($arr) function accepts a PHP array and returns a new array containing only its values (not its keys). Its counterpart is the array_keys() function. Use this function to retrieve all the values from an associative array.

$data = array("hero" => "Holmes", "villain" => "Moriarty");

[0] => Holmes
[1] => Moriarty