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.php209 chars8 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.php218 chars9 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