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:
- The first one is the element present in the array.
- The second is the array name.
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
Using array_flip()
The array_flip() function swaps keys and values in an array. You can use it to find the index of an element by flipping the array and checking if the element exists as a key. If it exists, its value will be the original index.
Example:
<?php
// Create an indexed array with 5 subjects
$array1 = array('php', 'java', 'css/html', 'python', 'c/c++');
// Flip the array
$flippedArray = array_flip($array1);
// Get the index of PHP
if (isset($flippedArray['php'])) {
echo $flippedArray['php'];
} else {
echo "'php' not found in array";
}
echo "\n";
// Get the index of java
if (isset($flippedArray['java'])) {
echo $flippedArray['java'];
} else {
echo "'java' not found in array";
}
echo "\n";
// Get the index of c/c++
if (isset($flippedArray['c/c++'])) {
echo $flippedArray['c/c++'];
} else {
echo "'c/c++' not found in array";
}
echo "\n";
?>
Output
0 1 4