Problem with Array Search in PHP
I am not finding what might be the problem in my program.
I am having an array like this
$arr = array("1", "urgent", "4", "low", "15", "avg");
When i am searching this array using
$key = array_search("4", $arr);// Working
Its is giving me the index of that element;
But when i am searching for "1" it is not giving me any index.
$key = array_search("4", $arr); // Not w开发者_JS百科orking here - for searching "1"
What might be the problem.
Thank You
http://ideone.com/e1n3r Your code does work fine. It returns key == 0, which is the key, where "1" is stored.
To get the difference between 0 and false
you should use ===
operator, or its contrary !==
:
$arr = array("1", "urgent", "4", "low", "15", "avg");
$key1 = array_search("1", $arr);
var_dump($key1 === false); // false (value exists)
var_dump($key1 !== false); // true (value exists)
$key21 = array_search("21", $arr);
var_dump($key21 === false); // true (value does not exist)
var_dump($key21 !== false); // false (value does not exist)
array_search return key value of array.
$arr = array("1", "urgent", "4", "low", "15", "avg");
$key = array_search("4", $arr);
// give output is 2 which is key value
$key = array_search("1", $arr);
//give output is 0 which is key value
I think you are using $key
in thewrong way. $key = 0
and now if you do boolean evaluation it will act as false. You should use something like if($key >= 0)
or if(is_int($key))
Remember that 0
is evaluated to FALSE
in php.
so..
if($index = array_search("1",$arr)) {
//will actually evaluate to false
}
In case you are using it this way and think it's not working because the conditional isn't technically failing, the value is evaluated as FALSE
.
精彩评论