Jump to content

Recommended Posts

I'm confused with some odd behaviour with foreach, if have the following code:

 

$arr = array ();
foreach ($arr['doesnotexist'] as $v) {
  // ...
}
print_r ($arr);
// Outputs: Array ( [doesnotexist] => )

 

So it creates $arr['doesnotexist'] as it was not set, however the following does not create anything:

 

foreach ($doesnotexist as $v) {
  // ...
}
print_r ($doesnotexist);
// Outputs nothing

 

Does anyone know why this happens, and if there's an alternative looping method??

My guess would be, in your first example you're not referencing just the array, but the array slice 'doesnotexist'. This doesn't exist, but since you're passing it to foreach in that manner, the fuction might be assuming that 'doesnotexist' is also an array. And since it doesn't exist, PHP is initializing it when you run foreach. At least, that's my theory.

robos you are incorrect. foreach loops do not initiate variables/array keys if they don't exist. If I run the following code:

<?php
$arr = array();
foreach($arr['test'] as $v)
{
    echo $v;
}

echo '<pre>' . print_r($arr, true) . '</pre>';

?>

I get the following output:

Notice: Undefined index: test in C:\Server\www\test.php on line 3

Warning: Invalid argument supplied for foreach() in C:\Server\www\test.php on line 3

Array
(
)

@robos

 

Yeah, I imagine it's something along those lines, however the datatype is actually set to "NULL" which I'm finding a little hard to understand

 

$arr = array ();
foreach ($arr['doesnotexist'] as $v) {
 // ...
}
print_r ($arr);
// Outputs: Array ( [doesnotexist] => )
echo gettype ($arr['doesnotexist']);
// Outputs: NULL

 

Maybe it's an internal problem / bug... Hmm

 

@wildteen

 

What version of PHP are you running to get those settings? I'm on PHP 4.3.9, safe mode is on

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.