Is possible PHP array id that not exist to be 0? - php

I have an array that can have a key "d" or not. The values associated with "d" comes from a mysql query. I don't want to show "d"'s value when it is
NULL
"NULL"
""
less than 0
So I have this scenario:
// should show
$a = array("a"=>1,"b"=>NULL,"c"=>"zzz");
if ($a["d"] >= 0) {
echo "show";
}
// should show
$a = array("a"=>1,"b"=>NULL,"c"=>"zzz","d"=>NULL);
if ($a["d"] >= 0) {
echo "show";
}
It seems that php is recognizing NULL as 0 when "d"=>NULL. What is the best way to test those conditions without using array_key_exists?

The reason that you think php is interpreting the value as 0 is because when you do the comparison, you're using >=.
>= will typecast the left value to the type of the right-side value. So the comparison actually looks more like
((int) $a["d"]) >= 0
and null, when cast to an int, is 0.
you can also check for the existence of that array index using
isset($a['d'])
or
empty($a['d'])
This is the downside of having a loosely typed language, it gets confusing if you don't fully understand whats goin on. check this out for a bunch more information

isset is your friend
<?php
$ar_list = array(
array('d' => null),
array('d' => 0),
array('d' => 12),
);
foreach ($ar_list as $ar) {
if (isset($ar['d']) && $ar['d'] >= 0) {
echo "{$ar['d']}\n";
};
};
The above example will output:
0
12

Related

Need exact reason for this logically condition failed

Why below code is printing the "here", it should be "there"
$a = "171E-10314";
if($a == '0')
{
echo "here";
}
else
{
echo "there";
}
PHP automatically parses anything that's a number or an integer inside a string to an integer. "171E-10314" is another way of telling PHP to calculate 171 * 10 ^ -10314, which equates to (almost) 0. So when you do $a == '0', the '0' will equate to 0 according to PHP, and it returns true.
If you want to compare strings, use the strcmp function or use the strict comparator ===.
when you use the == comparison, PHP tries to cast to different data types to check for a match like that
in your case:
'0' becomes 0
"171E-10314" is still mathematically almost 0 but I think PHP just rounds it to 0 due to the resolution of float.
check this link for a visual representation:
http://www.wolframalpha.com/input/?i=171E-10314
As per the answers given I tried to convert the string into numerical:
$a = "171E-10314" + 0;
print $a;
And I got output as 0.
Thats why it is printing here.
Use === /*(this is for the 30 character)*/

PHP with 2 conditions where 1 or the other can be true

I have two conditions. What I want to happen is if either of the conditions quantities are greater than zero then the appropriate message displays. What is happening is the messages are displaying only if _minLogo is greater than zero.
You have a comparison $this->_minLogo || $this->_minFreeLogo - the result of this is a boolean! And you can't iterate over a boolean. Use something like this
if ($this->_minLogo || $this->_minFreeLogo) {
if ($this->_minLogo)
$set = $this->_minLogo;
else
$set = $this->_minFreeLogo;
foreach ($set as $logo_type => $quantity) {
//etc.
}
}
Are either of those values guaranteed to be an integer? If statements can use integers and 'truthy' values (anything not 0 or NULL I think).
Anyways I think its better to be more specific in this case:
( ($this->_minLogo) > 0 || ($this ->_minFreeLogo) > 0)

Is this a PHP Bug? Run foreach over mixed array with an if

I was implementing the piwik api and I found unexpected behavior on my local copy of piwik. (The latest piwik version does not contain this piece of code anymore.)
Here is the bug:
<?php
$arrtest = array('label' => array(1,2,3), 0 => 'zero');
foreach($arrtest as $key => $value) {
if($key != 'label') {
var_dump($value);
}
}
?>
The given code should print string(4) 'zero' after skipping the 'label' key. But it does not print anything. if I replace the inner code with:
if($key === 'label') continue;
var_dump($value);
Then it prints: string(4) "zero"
Can anyone explain this?
Use strict comparison, always:
$key !== 'label'
With your original code $key != 'label', when 0 is compared to 'label', 'label' is actually coerced into a int, and because label does not start with a number, it is automatically coerced to 0, the default value of an int. You're now comparing 0 != 0, which of course is false.
Compare:
0 == 'label'; // true
0 === 'label'; // false
This is PHPs "unusual" type coercion rules in effect. In the loop instance you're interested in, $key is 0. Thus the comparison is if (0 != 'label'), comparing an integer to a string. In this instance, it will coerce the string to an integer using its inbuilt rules. This converts label to 0. So, 0 != 0 is the test, which fails.
As you've noticed, use type strict comparisons (which don't perform the type coercion), to avoid this.

foreach, unexpected result for element, which key is 0

I have this code
$arr = array(
"0"=>"http://site.com/somepage/param1/param2/0",
"1"=>"http://site.com/somepage/param1/param2/1",
"thispage" => "http://site.com/somepage/param1/param2/2",
"3"=> "http://site.com/somepage/param1/param2/3"
);
foreach ($arr as $k=>$v) {
if ($k == "thispage") {
echo $k." ";
}
else {
echo ''.$k.' ';
}
}
Its surprise, for first element "0"=>"http://site.com/somepage/param1/param2/0", not created link, (for other elements works fine)
If replace first element key 0 on something other, for example 4, now links created. What is wrong ?
This is happening because 0 == "thispage" and the first key is 0. To find out more about this, take a look at the PHP manual page about Type Juggling.
Use === ("is identical to") instead of == ("is equal to"), because 0 is equal to "thispage", but not identical.
This is what happens with ==:
$key takes the integer value of 0
PHP tries to compare 0 == "thispage"
in order to make the comparison, it needs to cast "thispage" to integer
the resulting comparison is 0 == 0, which is true
If you use ===:
$key takes the integer value of 0
PHP tries to compare 0 === "thispage"
since 0 is of a different type (integer) than "thispage" (string), the result is false
This is What you are doing wrong.
if ($k === "thispage") {
echo .$k." ";
}
Do the:
if ($k === "thispage")
You have to use identical comparison operator === as equal comparison operator won't help here, because
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.
thispage converted to number will return 0, so your if statement will match if you use equal comparison operator ==. When you do identical comparison === if type does not match it returns false.
You can read about comparison operators here.
Try this:
if ($k === "thispage") {
echo $k." ";
}
http://us.php.net/manual/en/language.types.array.php:
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08").
So in your case Stings "1", "2" and "3" are treated as integers.
To fix this use the === operator that check for type along with value.
The reason for the result you see is the comparison operator you use. == is too imprecise sometimes and can result in wierd things like this. Using the === will compare the values for exactness and will prevent the issue you have.
so:
foreach ($arr as $k=>$v) {
// this is the important thing
if ($k === "thispage") {
echo $k." ";
}
else {
echo ''.$k.' ';
}
}

PHP If Statement not working correctly, not null

I'm struggling to understand why my if statement below always results in false. I am creating a function which will test incoming connections to a script which will reject connections made by certain bots.
In my test below, on applying the if logic, I'm expecting a TRUE as both the array $value and $test value should match... resulting in a NOT NULL?
$bots = array(0 => "PaperLiBot", 1 => "TweetmemeBot", 2 => "Appsfirebot", 3 => "PycURL", 4 => "JS-Kit", 5 => "Python-urllib");
$test = strtolower("PaperLiBot");
foreach($bots as $value)
{
$i = strtolower(strpos($value, $test));
if ($i != NULL)
{
echo "Bot is found";
exit;
}else
{
echo "not found";
}
}
I think you are trying to accomplish this
foreach($bots as $value)
{
$i = strpos(strtolower($value), $test);
if ($i !== false){
echo "Bot is found";
exit;
}else{
echo "not found";
}
}
you want to write:
if(stristr($value, $test)){
// found
}else{
// not found
}
null in PHP is mutually type-castable to '0', '', ' ', etc... You need to use the strict comparisons to check for a 0-based array index:
if ($i !== NULL) {
...
}
note the extra = in the inequality operator. It forces PHP to compare type AND value, not just value. When comparing value, PHP will typecast however it wants to in order to make the test work, which means null == 0 is true, but null === 0 is false.
the correct way to check if a variable is set to NULL is:
if(!is_null($var)){
[my code]
}
the strpos returns a boolean, not a NULL value.
if you are unsure of the content of a variable, you can always debug it with a simple
var_dump($var);

Categories