PHP Behavior on array key exist check

39 views
Skip to first unread message

vishal

unread,
Jan 12, 2014, 4:46:22 AM1/12/14
to professi...@googlegroups.com
Hi All,

Following script giving some non expected result.

<?php
$myarray = array('firstName', 'lastName', 'companyName', 'jobTitle');
foreach($myarray as $attributeName=>$attributeData)
{
if(isset($attributeData['hiddenValue']) && !empty($attributeData['hiddenValue']))
     {
print $attributeData['hiddenValue']." testing<br/>";
}
}

Output:
f testing
l testing
c testing
j testing

Why on earth this $attributeData['hiddenValue'] consider first character in string? I found this coding bug in zurmo opensource CRM and giving failed test case result.
Is this the way php string to array behave?

Regards,
Vishal

Robert Gonzalez

unread,
Jan 12, 2014, 10:49:37 PM1/12/14
to professional-php
Is $myarray a true array or an instance of an Array object of some sort? I'm asking because in your example you would never get to your print statement because your isset/!empty check (which is redundant by the way) would always be false UNLESS the string 'hiddenValue' is somehow being cast to an integer. The integer value of the string 'hiddenValue' is 0, and since since $attributeData, in each iteration, is a string, the 0th character of the string would be it's first letter.


--
You received this message because you are subscribed to the Google Groups "Professional PHP Developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to professional-p...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--

Robert Gonzalez
   

vishal bhandare

unread,
Jan 14, 2014, 3:15:20 AM1/14/14
to Professional PHP Developers
Hi Robert,

$myarray is true array, I agree to your point 

The integer value of the string 'hiddenValue' is 0 
string 'hiddenValue' is somehow being cast to an integer

This statement helped me to debug more into details. I found below warning on php.net











vishal bhandare

unread,
Jan 14, 2014, 9:44:57 AM1/14/14
to Professional PHP Developers
Hi All,

Sorry for incomplete previouse mail. Below is warning found on



Warning

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NULL byte.


So any string offset to access character need to be integer else php will convert non-integer to integer that is 0. Hence will return first character


Regards,

Vishal



--

Reply all
Reply to author
Forward
0 new messages