Open In App

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

Last Updated : 26 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

Here we have some common approaches

Using array_search() Function

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

Using a custom function

We can create a custom function to iterate through the array and return the index of the desired element. This approach involves using a simple loop to check each element of the array.

Example: In this custom function, we use a foreach loop to iterate through the array. For each iteration, we check if the current element matches the given element. If a match is found, we return the index (or key) of the element. If no match is found after the loop completes, we return -1 to indicate that the element is not present in the array.

<?php
function findIndex($array, $element) {
    foreach ($array as $index => $value) {
        if ($value === $element) {
            return $index;
        }
    }
    return -1; // Return -1 if the element is not found
}

// Example usage for indexed array
$indexedArray = array('apple', 'banana', 'cherry', 'date');
$index = findIndex($indexedArray, 'cherry');
echo " The index of 'cherry' is: " . $index;
echo "\n";// Output: The index of 'cherry' is: 2

// Example usage for associative array
$assocArray = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry', 'd' => 'date');
$index = findIndex($assocArray, 'cherry');
echo "The index of 'cherry' is: " . $index; // Output: The index of 'cherry' is: c

?>

Output
 The index of 'cherry' is: 2
The index of 'cherry' is: c

Using a foreach Loop

Using a loop to find the index of an element involves iterating through the array with a foreach loop. Check each value, and if it matches the target element, store the current key as the index and exit the loop. This method ensures a manual search.

Example

<?php
$array = array("apple", "banana", "cherry");
$value = "banana";
$index = null;

foreach ($array as $key => $val) {
    if ($val === $value) {
        $index = $key;
        break;
    }
}

if ($index !== null) {
    echo "The index of '$value' is $index.\n";
} else {
    echo "'$value' is not found in the array.\n";
}
?>

Output
The index of 'banana' is 1.

Using array_keys Function

The array_keys function in PHP returns all keys of an array that match a specified value. By passing the value you want to find, you get an array of matching keys. Use `[0]` to get the first index if multiple matches exist.

Example:

<?php
$array = ['apple', 'banana', 'cherry', 'banana'];
$elementToFind = 'banana';

// Find all keys that match the value
$keys = array_keys($array, $elementToFind);

if (!empty($keys)) {
    echo "The element '$elementToFind' is found at indices: " . implode(', ', $keys);
} else {
    echo "The element '$elementToFind' was not found in the array.";
}
?>

Output
The element 'banana' is found at indices: 1, 3

Using array_map() Function

The array_map() function applies a callback function to each element of the array, allowing you to transform the array elements before searching for the index. This can be useful if you need to perform case-insensitive searches or other custom operations on the array elements.

Example: In this example, we use array_map() to convert all elements to lowercase before searching for the index of a particular element. This makes the search case-insensitive.

<?php
// Create an indexed array with mixed case elements
$array = array('Apple', 'Banana', 'Cherry', 'Date');

// Convert all elements to lowercase
$lowercaseArray = array_map('strtolower', $array);

// Search for the lowercase version of the element
$elementToFind = 'banana';
$index = array_search(strtolower($elementToFind), $lowercaseArray);

if ($index !== false) {
    echo "The index of '$elementToFind' is: $index";
} else {
    echo "'$elementToFind' was not found in the array";
}
?>

Output
The index of 'banana' is: 1

This approach is flexible because it allows you to manipulate the array elements before performing the search, making it adaptable to various use cases like case-insensitive searches, trimming whitespace, or applying other transformations.




Similar Reads

three90RightbarBannerImg