Monday, May 4, 2009

How to search an array in php

You can use array_search() function to easily search values in an php array. If you didn't know about this function you should have probarbly used a foreach or for loop to find a matching value in your array.

array_search() will return the array key if found the given value. This function is case sensitive to strings.


<?php

$my_array = array('1', 'kuppiya', 'Tom', 'Hello');

$key = array_search('Tom', $my_array);

if($key === false)
{
echo 'Not found';
}
else
{
echo $my_array[$key];
}

?>

No comments:

Post a Comment