Array key comparison fails - php

For some reason when I iterate through an array using foreach loop a condition fails comparing the key with a string. My array has two indexes the first one is an integer and the second one is an string.
$firmas[] = $credito['acreditado'];
$firmas['cbi'] = "LIC. MARCELA SOTO ALARCĂ“N";
I want to do something else when the loop finds that the key in that moment is the string one but for some reason when I evaluate the integer index the result is true.
foreach($firmas as $key => $firma){
var_dump($key);
var_dump($key=='cbi');die();
}
The output is
int(0) bool(true)
But as you can see the condition is looking for the string 'cbi' so the result should be false with the integer index and true for the string.
What's happening here?

In PHP, all strings are equal to 0, though not equivalent to it. Try using === instead of just ==.
Addendum: all strings that do not begin with numbers are equal to 0.

Related

array_search can't find element which is clearly there

Why does the following code work:
$test = array(0=>'test1','field0'=>'test2',1=>'test3','field1'=>'test4');
echo array_search('test4',$test);
But the following doesn't:
$test = array(0=>0,'field0'=>'test2',1=>'test3','field1'=>'test4');
echo array_search('test4',$test);
If you had a mixed array from say mysql_fetch_array($result,MYSQL_BOTH) and took the keys which you needed to search you wouldn't be able too - it would never progress further than 0.
Try to do array_search('test4',$test, TRUE);. The 3rd parameter tells it to use === instead of == when comparing.
Since your array holds both strings and numbers, when it compares to the 0 (the 1st element), it converts 'test4' to a number (it stops at the 1st non-numeric character) and it happens to match.
What I mean is: 'test4' == 0 => 0 == 0 => true.
When you pass TRUE as the 3rd parameter, it uses ===, and 'test4' === 0 is automatically false since the types don't match, there is no conversion.
The solution = force the 0 value to be a string:
$test = array(0=>0,'field0'=>'test2',1=>'test3','field1'=>'test4');
foreach ($test as $k=>$v){ $test[$k] = (string) $v; }
echo array_search('test4',$test);
You can't search a number for a string and expect a good result.
My guess is it sees the value as a number, so it converts your string to a number (which it can't) so that string gets converted to a 0. So the value of 0 equals the search string, which also equals 0, and there's your result.
If the value is 1, it won't match as the search string gets converted to a 0 (as you can't convert a string to a number) so it wouldn't match in the following.
$test = array(0=>1,'field0'=>'test2',1=>'test3','field1'=>'test4');
You'll only get your exact case scenario when that value in the array is 0.

if loop failing not if clause in PHP

I have the following code for PHP
if ($checkimghash != $imghash)
{
the $checkimghash is var_dumped as this array(2) { [0]=> string(40) "da77c24758c6259274bfa171a32d5c4a4a2cb71c" ["PdfHash"]=> string(40) "da77c24758c6259274bfa171a32d5c4a4a2cb71c", the variable $imghash var_dumps as this
string(40) "da77c24758c6259274bfa171a32d5c4a4a2cb71c,
Why is this check running despite the equal results? I thought != needs to pass both type and value checks
Because you are comparing an array to a string and they are not the same
try changing your test to
if ($checkimghash[0] != $imghash)
!= is value, !== is value and type
!= is only comparing the value. It's opposite is ==
TRUE if $a is not equal to $b after type juggling.
!== is comparing both the value and the type. It's opposite is ===
TRUE if $a is not equal to $b, or they are not of the same type.
Source: http://www.php.net/manual/en/language.operators.comparison.php
Edit
The var_dump result in your question is unclear. If you are comparing an array with a string, then they are always different. You may want to compare the value of an element of an array with another string by $array[0]
Because if $checkimghash is an array and $imghash a string then the two won't directly compare (in any meaningful sense), as you're comparing an array (i.e. a collection of strings) to a string! select the element of the array you'd like to compare and use that in the condition.

Foreach loop issues in php

Here is some code I have: (p just echos plus adds a newline)
foreach ($vanSteps as $k => $reqInfo)
{
p($k);
if ('van' == $k) { p('The key is the van, continue'); continue; }//continue if we reached the part of the array where van is key
//do stuff
}
and I'm getting this output:
0
The key is the van, continue
1
2
3
van
The key is the van, continue
Why does the if statement return true when the key is 0? This foreach loop handles logic that applies when the key == 0 (and any other key except if the key is 'van') and this messes up the logic because it's return true when key is 0.
Any help?
Thank you.
Use === for this comparison. When PHP compares string and integer it first casts string to integer value and then does comparison.
See Comparison Operators in manual.
In PHP 'van' == 0 is true. This is because when using == to compare a string and a number, the string is converted to a number (as described in the second link below); this makes the comparison internally become 0 == 0 which is of course true.
The suggested alternative for your needs, would be to use a strict equality comparison using ===.
See Comparison Operators and String conversion to numbers
In PHP, when you compare 2 types, it has to convert them to the same type. In your case, you compare string with int.
Internally this gets converted to
if((int)'van'==0)....
and then
if((int)'van'==1)....
(int)'any possible string' will be 0:) So you either have to manually convert the both values to the same type, or use === as a comparison operator, instead of the loose =.
An exception from this rule(as pointed out in the comments) would be if the string start with a number, or can be interpreted as a number in any way(1, 0002, -1 etc). In this case, the string would be interpreted as a number, diregarding the end of the non-numeric end-of-string
Take a look at http://php.net/manual/en/types.comparisons.php for more details.
This works fine:
$array = array(0=>"a",1=>"b","van"=>"booya!");
function p($v){ echo "{$v}<br />"; }
foreach ($array as $k => $reqInfo)
{
p($k);
if ('van' === $k) { p('The key is the van, continue'); continue; }//continue if we reached the part of the array where van is key
//do stuff
}
Output:
0
1
van
The key is the van, continue
Note the ===.
Read the Comparison with Various Types table
When one of the operand is number, the other operand is converted to number too. Since 'van' is non-numeric sting, it's converted to 0. You should use === operator in the case, which also checks the variable type
That's becuase 'van' == 0 (true).
Instead, you should use 'van' === 0 (false).
In short, use === instead of ==.
Its interpreting the 'van' as a boolean value (false) which 0 is equal to.
To check for exact matches in type and value in PHP you must use === instead of ==

PHP: Check if 0?

I am using a class which returns me the value of a particular row and cell of an excel spreadsheet. To build up an array of one column I am counting the rows and then looping through that number with a for() loop and then using the $array[] = $value to set the incrementing array object's value.
This works great if none of the values in a cell are 0. The class returns me a number 0 so it's nothing to do with the class, I think it's the way I am looping through the rows and then assigning them to the array... I want to carry through the 0 value because I am creating graphs with the data afterwards, here is the code I have.
// Get Rainfall
$rainfall = array();
for($i=1;$i<=$count;$i++)
{
if($data->val($i,2) != 'Rainfall') // Check if not the column title
{
$rainfall[] = $data->val($i,2);
}
}
For your info $data is the excel spreadsheet object and the method $data->val(row,col) is what returns me the value. In this case I am getting data from column 2.
Screenshot of spreadsheet
Did you try an array_push() ?
array_push($rainfall, $data->val($i,2));
I would use a strict comparison with the not identical operator here instead of using the not equals operator:
if($data->val($i,2) !== 'Rainfall')
If $data->val($i,2) is an integer and you use == both sides will be cast to integers which would give you the result that all integers would work as you expect except for zero. Here's a summary of the difference between == and === when comparing the string "RainFall" with zero:
0 == "RainFall" : true
0 != "RainFall" : false
0 === "RainFall" : false
0 !== "RainFall" : true
I think that the array is treating the 0 like false, which could explain it not going into the array. Would something like this work (if you are using integers)?
(int)($data->val($i,2));
or
(float)($data->val($i,2);)
The problem lies in the if statement. You're trying to compare a string with an integer, which according to the PHP documentation will typecast both to integers.
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
You can read more here http://php.net/manual/en/language.operators.comparison.php.
Update: The if statement won't work in the case of 0 because (int)"Rainfall" will by typecasted into 0 by PHP causing the statement to be if (0 != 0) { ... }.
If $i represents the row number, why don't you start from 2 instead of 1?

PHP Does if (count($array)) and if ($array) mean the same thing?

In PHP, will these always return the same values?
//example 1
$array = array();
if ($array) {
echo 'the array has items';
}
// example 2
$array = array();
if (count($array)) {
echo 'the array has items';
}
Thank you!
From http://www.php.net/manual/en/language.types.boolean.php, it says that an empty array is considered FALSE.
(Quoted):
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Since
a count() of > 0 IS NOT FALSE
a filled array IS NOT FALSE
then both cases illustrated in the question will always work as expected.
Those will always return the same value, but I find
$array = array();
if (empty($array)) {
echo 'the array is empty';
}
to be a lot more readable.
Note that the second example (using count()) is significantly slower, by at least 50% on my system (over 10000 iterations). count() actually counts the elements of an array. I'm not positive, but I imagine casting an array to a boolean works much like empty(), and stops as soon as it finds at least one element.
Indeed they will. Converting an array to a bool will give you true if it is non-empty, and the count of an array is true with more than one element.
See also: http://ca2.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

Categories