Page 1 of 1
array_search problem
Posted: Sat Mar 14, 2009 1:14 am
by susrisha
Can you please tell me what am i doing wrong?
I am trying to implement as well learn the basic array_search function.
Code: Select all
$my_array = array('pop','rock');
print_r($my_array);
if(array_search('pop',$my_array))
{
echo "String found";
}
else
{
echo "String not found in the array";
}
The out put shows "String not found in the array"..
Re: array_search problem
Posted: Sat Mar 14, 2009 1:21 am
by susrisha
okay sorry for the trouble.. i have solved it myself.. Here it is..
output :
Code: Select all
Array
(
[0] => pop
[1] => rock
)
String not found in the array
In the code i am trying to check if there exists any key.. yaa a key does exist for 'pop' in the array but the value of the key is 0 which by default is taken as false by the if statement.
Hence the trouble.. I have modified it as
Code: Select all
if(array_search('pop',$my_array)||($my_array[0]=='pop'))
Re: array_search problem
Posted: Sat Mar 14, 2009 1:52 am
by php_east
the function returns key, and possible key values are 0..n.
so i like to use
Code: Select all
if (array_search('pop',$my_array)>-1)
so it is correct to test if the
function executed by using false, but not correct to test for if is in array using if (key). instead if (bool) should be used, which is what >-1 returns.
Re: array_search problem
Posted: Sat Mar 14, 2009 6:12 am
by hasti
Hi
you can use the in_array function also
Code: Select all
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>
Re: array_search problem
Posted: Sat Mar 14, 2009 9:40 am
by JasonDFR
I think this is a mistake a lot of programmers make. You should always know what the return values of a function are and test for those. array_search returns false on failure. So test for that.
Code: Select all
if(array_search('pop',$my_array) [i]!== false[/i])
would be the best.
in_array would work, unless you need the key.
And I have made this same mistake, more than once. Although the second time I figured it out a lot quicker than the first.