array_search problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
susrisha
Forum Contributor
Posts: 439
Joined: Thu Aug 07, 2008 11:43 pm
Location: Hyderabad India

array_search problem

Post 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"..
User avatar
susrisha
Forum Contributor
Posts: 439
Joined: Thu Aug 07, 2008 11:43 pm
Location: Hyderabad India

Re: array_search problem

Post 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'))
 
User avatar
php_east
Forum Contributor
Posts: 453
Joined: Sun Feb 22, 2009 1:31 pm
Location: Far Far East.

Re: array_search problem

Post 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.
hasti
Forum Newbie
Posts: 6
Joined: Sat Mar 14, 2009 5:37 am
Location: India
Contact:

Re: array_search problem

Post 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";
}
?>
JasonDFR
Forum Commoner
Posts: 40
Joined: Wed Jan 07, 2009 3:51 am

Re: array_search problem

Post 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.
Post Reply