Open In App

How to find the index of an element in an array using PHP ?

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.

Syntax:



array_search('element', $array)

Parameters:

Return Value: It returns the index number which is an Integer.



Note: We will get the index from indexed arrays and associative arrays.

Example 1: PHP program to get the index of the certain elements from the indexed array.




<?php
  
// Create an indexed array with 5 subjects
$array1 = array('php', 'java'
         'css/html', 'python', 'c/c++');
  
// Get the index of PHP
echo array_search('php', $array1);
echo "\n";
  
// Get the index of java
echo array_search('java', $array1);
echo "\n";
  
// Get the index of c/c++
echo array_search('c/c++', $array1);
echo "\n";
  
?>

Output
0
1
4

Example 2: The following example returns the index of an associative array.




<?php
  
// Create an associative array
// with 5 subjects
$array1 = array(
      0 => 'php'
      1 => 'java',
      2 => 'css/html'
      3 => 'python',
      4 => 'c/c++'
);
  
// Get the index of php
echo array_search('php', $array1);
echo "\n";
  
// Get the index of java
echo array_search('java', $array1);
echo "\n";
  
// Get index of c/c++
echo array_search('c/c++', $array1);
echo "\n";
  
?>

Output
0
1
4

Article Tags :