Jump to content

Array and loops


MetalSmith

Recommended Posts

Man this is really driving me nuts. I can see my array values with echo inside the loop but outside nothing is shown. What am I missing here? If anything it should show the last value in the loop.

 

while ($x = mysql_fetch_array($query_name,MYSQL_NUM))

{

echo $x[0];

}

echo $x[0];

 

Link to comment
Share on other sites

Thanks for the help Jcbones. Sorry for the noob questions but I have one more :) How come the this piece of code automatically fills the $a array? What is it about the [] on the $a & $x that makes it fill up?

 

$a = array();

while ($x = mysql_fetch_array($query_name,MYSQL_NUM))

{

$a[] = $x[0];

}

echo ($a[0]);

 

Link to comment
Share on other sites

I'm not real good at explanations, but I'll try to be clear.

 

$a = array(); //define $a as an empty array.
while ($x = mysql_fetch_array($query_name,MYSQL_NUM)) //mysql_fetch_array will return false after the resource handle has run out, so when the query is empty, $x = false which breaks the while loop.
{
$a[] = $x[0]; //if $x is passed to the while loop, it will contain an array full of row data. Currently you are asking it to only pass the first value to the $a array.
//You then append this data to the $a array ([] denotes an array.)
}
echo ($a[0]); //you only echo the first value from the $a array.

 

Arrays explained better than I ever could

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.