How to Find the Index of Element in Array Using PHP?

03-Apr-2023

.

Admin

How to Find the Index of Element in Array Using PHP?

Hi Dev,

In this article, we will discuss how to find the index of an element in an array in PHP.Array indexing starts from 0 to n-1. We can get the array index by using the array_search() function. This function is used to search for the given element. It will accept two parameters.

There are example to check if how to find the index of element in array using php. in this example, we will use to array_search() function to check if how to find the index of element in array using php. so let's thefollowing example with output.

Example 1:


index.php

<?php

// Create an indexed array with 5 colors

$colors = array('orange', 'yellow', 'green', 'indigo', 'purple');

// Get the index of PHP

echo "<pre>";

echo array_search('orange', $colors);

echo "\n";

// Get the index of green

echo array_search('green', $colors);

echo "\n";

// Get the index of purple

echo array_search('purple', $colors);

echo "\n";

?>

Output:

0

2

4

I hope it could help you...

#PHP