Jump to content

Why does foreach create a new variable if there is none set?


david-king

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.