Programming Tutorials
PHP IndexOf Key like JavaScript
Many beginners to PHP wonder about how they use to do something in another language. One question that comes up often is, how do you use indexOf like in JavaScript in PHP? Well you can either use the following code or array_search function.
The following function is just like the indexOf function in JavaScript. In fact, there is no PHP equivalent.
Simply enter your needle or the value of the array you are looking for and the array haystack to search in. Example: $ArrayIndexNumber = indexOf($thisValue, $BigArray);
function indexOf($needle, $haystack) { for($i = 0,$z = count($haystack); $i < $z; $i++){ if ($haystack[$i] == $needle) { //finds the needle return $i; } } return false; }
The alternative is to use PHP's built-in array_search() function. However, array_search only returns the Key value, not the Key index number.
$array = array('fruit_1' => 'orange', 'fruit_2' => 'apples', 'fruit_3' => 'awesome_fruit'); $keyName = array_search('apples', $array); // $keyName is 'fruit_2' // do not expect array_search to work the same as indexOf.


Post new comment