To get the index of a specified element in an array in PHP, you can use functions like array_search
.
In this example,
$numbers
with values 10, 20, 30, 40, 50.array_search
function to find the index of a specific element in the array.array_search
function returns the index of the element, or false if the element is not found.<?php
$numbers = [10, 20, 30, 40, 50];
$index = array_search(30, $numbers);
echo 'Index of element 30 is: ' . $index;
?>
Index of element 30 is: 2
In this example,
$fruits
with values 'apple', 'banana', 'cherry'.array_search
function to find the index of a specific element in the array.array_search
function returns the index of the element, or false if the element is not found.<?php
$fruits = ['apple', 'banana', 'cherry'];
$index = array_search('banana', $fruits);
echo 'Index of "banana" is: ' . $index;
?>
Index of "banana" is: 1
In this tutorial, we learned How to get the Index of Specified Element in an Array in PHP language with well detailed examples.