(array)$someemptyvariablethatisnotarray returns array([0] =>) instead of array()
How can I make it so I get a empty array that is not iterated when I'm using it inside foreach() ?
The feature which you are using, is called "casting". This means a variable is forced to become a given type, in your example an array. How the var is converted is not always obvious in PHP!
In your example $someemptyvariablethatisnotarray becomes an array with one entry with a NULL value.
The PHP documentation says:
The behaviour of an automatic conversion to array is currently undefined.
To solve your code I would recommend something like this:
if (!is_array($someemptyvariablethatisnotarray) {
$someemptyvariablethatisnotarray = array();
}
$somevar = empty($somevar) ? array() : (array)$somevar;
Maybe? Though I'm not sure I get the cast, or the purpose. Care to ellaborate a bit more (maybe an example of what you're trying to accomplish?)
foreach((array)$something as $k).... Sometimes $something may be "false" and not a array, so I don't want foreach to iterate itwhile (($row = mysql_fetch_array($result)) !== false){ ... }. That's still a "check". ;-)how are you?
I believe this is what you're after:
$something = false;
foreach((array)(empty($something) ? null : $something) as $k){
echo 'never enters here';
}
You don't get an empty array, because when you set "(array)false", it means you'll have a single element, and that element will have the "FALSE" value assigned to it.
Same happens with an empty string (not a null one!) (array)$emptystring will return an array which contains a single element, which is an empty string!
Similar to doing:
array('');
Hope it helps.
Cheers!
var_dump()instead ofprint_r()it shows you also the type of the value in the array!