Monday 24 November 2014

PHP array search

Search in array



Somtimes you have a quite big array which is filled up from a file or code. In this case you don't know whether a given value exists in the array or not. And if it exists then it would be fine to get the key of this element. 

Let's suppose you have the following array: 
Code:
  1. $colorList = array("apple"=>"red",
  2. "grass"=>"green",
  3. "sky"=>"blue",
  4. "night"=>"black",
  5. "wall"=>"white");

Now if you want to know whether the value "blue" exists you can use the PHP built in functionarray_search(). With this you can easy get this information in the following way: 
Code:
  1. echo 'Blue is '.array_search("blue",$colorList);

0 comments:

Post a Comment