...

View Full Version : Passing back arrays from functions



snoodle
07-26-2007, 06:24 PM
having a bad morning... just trying to pass back a simple array of sql id's...

<?php


THIS DOES NOT WORK...
function GetArray()
{
for ($i=0; $i < 3; $i++)
{
...
$id= mysql_insert_id();
$array[$i] = $id;
}
return $array;
}
.....
$myIDs = GetArray();
echo "firstID=".$myID[0]; displays firstID=


THIS, TOO, DOES NOT WORK...
function GetArray()
{
$ids = Array();

for ($i=0; $i < 3; $i++)
{
...
$id= mysql_insert_id();
$ids[$i] = $id;
}
return $ids ;
}
.....
$myIDs = GetArray();
echo "firstID=".$myID[0]; displays firstID=
?>
------------------------------------
Looking through my code I realize that I haven't yet had ocassion to pass arrays to/from functions. Examples I've look at online and in my PHP book look like the above, but when I check the return values I get zilch. I've also tried passing the array in as an argument but am getting the same thing.
----------------------------------------

weird... even if i make the array a global i have the same problem.... what am i doing wrong? if i fill the array in a function... then examine the values in another function, i just get nulls when i examine the array contents.

snoodle
07-26-2007, 07:22 PM
this is baffling...

<?php

myarray = array();

myfunc();

function myfunc();
{
global myarray;

myarray[0]="123";
echo "val=".myarray[0]; shows... val=123
}

function anotherfunc()
{
global myarray;
echo "val=".myarray[0]; shows... val=
}

?>

What am I missing??

matak
07-26-2007, 08:09 PM
Try using array_push, it worked for me. But i'm stuck on other problems now

eg.



<?php

$some_array = array ("Value1", "Value2", "Value3");

function getNewArray($some_array) {

$newArray = $some_array; #Of course some array can be defined with mySQL or any other functions

#you can use array_push function if you feel that it's more usefull
/*test this too
$newArray = array();

array_push ($newArray, $some_array);

*/
return $newArray;
}
?>

Structure looks like this for now <br>
<pre>
<?php
print_r (getNewArray($some_array));
?>
</pre>
<?php

function useArray ($array) {

foreach ($array as $key) {

echo "Array value/key is: ".$key."<br />";
}

}
useArray (getNewArray($some_array));
?>


I'm sure there's a more convinient way, but i hope this sets you on the right track...

snoodle
07-26-2007, 08:32 PM
jeez... sorry about this... it was all my fault... i was using the wrong value to index into the array. just another stupid mistake. it's becoming more and more evident that i need to start using a real php debugger. i've wasted so much time tracking code only to find little, dumb mistakes that would have become instantly obvious had i been using a real debugger instead of sticking in echos here and there.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum