find the index of an element in an array in php

To find the index of an element in an array in PHP, you can use the array_search() function. It returns the index of the first occurrence of the searched element in the array or returns false if the element is not found. Here's an example code:

main.php
$fruits = array('apple', 'banana', 'orange', 'grape');
$index = array_search('orange', $fruits);
if ($index !== false) {
    echo "The index of 'orange' is " . $index;
} else {
    echo "Element not found";
}
209 chars
8 lines

The above code will output the index of the element 'orange' in the array which is 2.

Alternatively, you can also use a loop to search for the element and return the index:

main.php
$fruits = array('apple', 'banana', 'orange', 'grape');
$search = 'orange';
foreach ($fruits as $index => $value) {
    if ($value == $search) {
        echo "The index of '$value' is " . $index;
        break;
    }
}
218 chars
9 lines

This code will output the same result as the previous one. The break statement is used to exit the loop once the element is found to avoid unnecessary iterations.

gistlibby LogSnag