PHPFront

Home > PHP > Return an Array key using a search term
The PHP website created by its users!



Return an Array key using a search term


AuthorMatthew
DescriptionSearches an array for a selected string and if it is found returns the key to which that string is stored in the array.
RatingThis script has been rated 4/5 (4 votes)

PHP Code


<?php

/***********************************************************************
* Use
*
* $needle // The item you are looking for
* $array // The array you are searching in
*
* // Return the key 
* $array_key = array_searcher($needle, $array);
* echo "The array's key is : " . $array_key;
***********************************************************************/ 
function array_searcher($needle$array)
    {
    
// Make sure a valid array was passed
    
if(!is_array($array))
        {
        return 
"Not a valid array";
        }

    
// Loop through each part of the array
    
foreach ($array as $key => $item)
        {
        
// Inner loop
        
foreach($item as $entity)
            {
            
// Found a match, return the key
            
if ($entity == $needle)
                {
                return 
$key;
                }
            }
        }
    }

?>



Rate it: Print Print

Comments


No comments posted yet.

Name
Website
Your comment