0 in $_GET is empty in PHP
Whilst at work,
I was writing a cart for an e-commerce site I am building.
The Cart consisted of a multi-dimensioned array, part associative, part indexed, anyway of note here is that,
A. It was an array.
B. The contents where indexed numerically
C. Arrays as you know begin at zero.
When removing an element from the cart, the elements indexed value, is passed via GET to be handled via the object, for removal.
It seemed to work fine, until I attempted to remove the first element, after a little debugging, I noticed the “0” value was being interpreted by PHP as empty?
WTF?
A quick mock up code later
1 2 3 | <?php if (!empty($_GET['get'])) echo "I RECIEVED A GET WITH VALUE: ".$_GET['get']; ?> |
and a check in the url
nameOfFile.php?get=1 displayed “I RECIEVED A GET WITH VALUE: 1”
nameOfFile.php?get=0 displayed “”
It seems that according to PHP the value zero is interpreted as empty because it is being handled as a string when used within GET.
But…………….
A string, as the name suggests is just a string of characters, strung together, it is an array of characters, or bytes, the fact that it held zero, would be irrelevant would`nt it not?
I can understand if it was attempting to cast the datatype to an integer, but again, zero is still zero.
The only scenerio I can see this being valid if it where NULL!
PHP uses loose datatypes or lucid?
15,079 views
This entry was posted on Wednesday, November 12th, 2008 at 9:39 pm and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed.
arrays starting at zero hurumpf always prefered the FORTRAN default of 1 which is how God (aka Dan McCracken) wants it.
you probaly need to use one of teh many equels sings php has == or === maybe
I am so glad you posted this. I spent 3 hours today trying to figure out why my empty _GET text box was not being ignored in an “if statement”. And then I found your blog post…
Awesome. Thanks.
Eli
Thank you Adrian! 🙂 was starting to think I had lost my mind. Damn loosely typed languages, lol.
I was trying to validate a select box. It’s input could be only 0 to 10, whenever I selected ‘0’. It failed. So I just changed the values from 1 to 11. Works fine now.
Thanks again,
Matt.
http://www.php.net/manual/en/function.empty.php#103756