[KLUG Programming] PHP arrays vs. structures
bill
bill at billtron.com
Mon Jul 19 14:56:49 EDT 2004
On Mon, 2004-07-19 at 13:46, Adam Tauno WIlliams wrote:
> > > if (key($value) == '0') {
> >
> > Isn't this a string comparison as you have 0 in single quotes? If
> > you're looking for integers, why not drop the quotes or consider using
> > ===?
>
> It is a good question. Documentation did not make it clear if key(...)
> returns a type:mixed or a type:string. Internally I think how PHP4
> handles types is a bit loosey-goosey; nice for somethings but
> jaw-grinding for others. The examples (the ones I glanced at anyway)
> seemed inconsistent among themselves.
>
> http://us2.php.net/key says key(....) returns mixed, so you're probably
> correct, that the ticks/quotes are inappropriate.
I think the result would have to be mixed because sometimes it is a
string, and sometimes an integer.
> > I don't know for sure that it will ever cause problems the way you're
> > doing it, just a note on the type of comparison it will do. I'm always
> > leery of comparing anything to zero because it reminds me of how I've
> > seem people look for results of functions (because return false can
> > evaluate to zero). If a function returns zero it is usually not the
> > same as returning false.
>
> Correct, I'm relying on foreach(...) to exhibit sane behaviour so that I
> don't walk of the end of the array (which PHP permits), at which point
> I'd assume key(...) would return 0, or false ???? I've never had any
> problem with foreach(...)
if ($somevariable == 0)
is subtly different from
if (thereturnofsomefunction() == 0)
For the second, what will happen if the function returns false? What
will happen if the function returns true with the integer zero? In all
cases, do we want to use this practice when there could be this
confusion? I often use the not operator !
if (!thereturnofsomefunction())
But that's because the new comparison, the triple equal sign, wasn't
available years ago. I think it may be time for me to change my
practice.
Consider the following
function gofalse() {
return FALSE;
}
if (!gofalse()) {
echo "this function result is false<br />";
}
if (gofalse() == 0) {
echo "this function result looks like zero<br />";
}
if (gofalse() === 0) {
echo "this function result is really the integer zero<br />";
}
function gozero() {
return 0;
}
if (!gozero()) {
echo "this function result is false<br />";
}
if (gozero()==0) {
echo "this function result looks like zero<br />";
}
if (gozero() === 0) {
echo "this function result is really the integer zero";
}
The only difference would be in the last comparison, the triple equal
sign. In the first case only the triple equal sign won't evaluate to
true. In the second, it will. Being as you're looking for an integer
instead of a function result, I'd use the triple equal sign.
kind regards,
bill
More information about the Programming
mailing list