Greetings, Dikkie Dik.
In reply to Your message dated Saturday, June 28, 2008, 16:24:57,
Quote:
Quote:
>At the moment I am trying to make my code run cleanly even if warnings
>are switched on. If I do a foreach on a non-existent array, I get a
>warning.
>>
>So I have to do
>>
>if($array) foreach($array as $foo){};
>>
>foreachif would only run if the array was not empty.
Quote:
You can off course suggest such a function. However, the site of PHP
would probably be a better place.
Quote:
Apart from that, your workaround tell something really funny: that the
variable $array is a boolean, and if true, it should be iterated upon as
if it were an array.
Quote:
I KNOW about type juggling, but this is what your code tells me. If you
want to check for an empty array, it would be much clearer to check for
a count being more than zero, or even write a function IsArrayFilled to
check if it is an array at all.
$var = 1;
echo count($var);
Read documentation :) It is clearly explained in the desctiption of count()
function.
To make sure you are operating with array, use straightforward is_array() type
check. If you want to check if it has any elements, you may combine it with
count(), but it is often a waste of mind.
I.e.
function doSmth($var)
{
$result = '';
if(is_array($var) && count($var))
{
foreach($var as $key =$value)
{
$result .= "[{$key}] ='{$value}'\n";
}
}
return $result;
}
and
function doSmth($var)
{
$result = '';
if(is_array($var))
{
foreach($var as $key =$value)
{
$result .= "[{$key}] ='{$value}'\n";
}
}
return $result;
}
will have the same result when $var = array();, but second code much clearer
to my taste.
Quote:
And, off course, there is no problem iterating over an empty array.
There will just be no iteration. Why put an if statement in front of it?
Is this a needless optimization? I think such an optimization is not
necessary, and if it is, it should not surprise me if it was alreadu
built in in the foreach statement.
--
Sincerely Yours, AnrDaemon <anrdaemon@freemail.ru>