array_search(): searching for value inside

Searching array This function Searches for presence of an input value.

Returns the key of matching element ( present ) , returns false if not found.

bool = array_search ($search, $input_array,$strict);
$search : Required , value to search inside the $input_array.
$input_array : Required , array inside which the value will be searched.
$strict :Optional : If set to TRUE then strict type comparison is performed.

Output is the corresponding key if value is found inside array , otherwise FALSE.
arra_search() returns the key of first occurrence of the value, to get the keys of all the matching values we can use array_keys() function

Example 1


echo "Value is available ";	
echo "Value is NOT available ";	
Output is here.
Value is available

Example 2

$input=array('One' =>1,'Two'=>2,'Three'=>3,'Four'=>'Fourth');

echo "Value is available ";	
echo "Value is NOT available ";	
Output is here.
Value is available

Example 3 , returning the matching key

$input=array('One' =>'First','Two'=>'Second','Three'=>'Third','Fourth');

$search_string='Third'; // Change this value
echo "Value <i>$search_string</i> is available inside array<br>";	
echo "Marching Key is : ".array_search($search_string,$input);
echo "Value <i>$search_string</i> is NOT available inside array <br>";	
Output is here
Value Third is available inside array
Marching Key is : Three
More functions to search an array.
in_array()Search for value inside Array. Returns TRUE or FALSE
array_key_exists()Returns TEUE if key is found inside, FALSE otherwise
array_keys()Array of keys for matching values, FALSE otherwise

Example 4

Here is an array of students where name of the student is key and mark is stored as value. Collect the highest and lowest mark ( values here ) along with the student names ( keys here ) . Used array_search() to collect the key ( student name )

echo "highest mark : ". max($student); // output 25
echo "<br>";
echo "Student got highest mark:".array_search(max($student),$student);
echo "<br>";
echo "Lowest mark : ". min($student); // output 13
echo "<br>";
echo "Student got Lowest mark:".array_search(min($student),$student);
Output is here.
highest mark : 25
Student got highest mark : Geek
Lowest mark : 13
Student got Lowest mark : Alex
Difference between arrays considering values
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2022 All rights reserved worldwide Privacy Policy Disclaimer