The Most Active and Friendliest
Affiliate Marketing Community Online!

“Adavice”/  “1Win

Tip : Searching in array in php

D

dman_2007

Guest
If want to search an array to see if it currently holds a particular value or not, then you have a couple options which you can use :

1) in_array function

in_array function takes two required arguments, first is the value which is being searched and second is the array which is to be searched for the presence of that particular value. in_array function will return true if it finds the value in the array otherwise it returns false. If the value being searched is a string then comparison will be case-sensitive. Also, note that in_array uses == by default for comparison, so it will match 0 to "invalidnumberstring" for example. If you want in_array to use === for comparison, you can indicate this to in_array by passing a boolean value true as third argument. Here's an example :

Code:
<?php
  $array1 = array(1, 2, 3, 4, 5, 6, 'joe');
    
  if(in_array(1, $array1))
  {
    echo '1 is present in the array<br />';
  }
  
  if(in_array(0, $array1))
  {
    echo '0 is present in the array (when not passing third argument)<br />';
  }
  
  if(in_array(0, $array1, true))
  {
    echo '0 is present in the array (when passing third argument)<br />'; 
  }
  else
  {
    echo '0 is not present in the array (when passing third argument)<br />';
  }

  if(in_array('JOE', $array1))
  {
    echo 'JOE is present in the array<br />';
  } 
  else
  {
    echo 'JOE is not present in the array<br />';
  } 
?>

the above code produces following output :

1 is present in the array
0 is present in the array (when not passing third argument)
0 is not present in the array (when passing third argument)
JOE is not present in the array

in my next post i will discuss the second method.
 
2) array_search function

array_search function is similar to in_array function takes same argument and behaves exactly like in_array function except for the value it returns. Unlike in_array function, array_search function return the key of the value when the search is successful (key of first matched element) and false when the search is unsuccessful. Since an element can have a numeric key 0 which converts to false when converted into a boolean value, make sure you use === comparison operator when determining that a search was successful or not.

If you wish to retrieve the keys of all matching elements instead of retreiving the key of just the first matching element, you can use array_keys function.
 
Array search function is :-
The array_search() function search an array for a value and returns the key.
array_search(value,array,strict);
_________________________________________________________________
Web site design
 
Last edited by a moderator:
PHP:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>
 
MI
Back