How to find the index of an element in an array using PHP ?
Last Updated :
13 Oct, 2021
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
<?php
$array1 = array ( 'php' , 'java' ,
'css/html' , 'python' , 'c/c++' );
echo array_search ( 'php' , $array1 );
echo "\n" ;
echo array_search ( 'java' , $array1 );
echo "\n" ;
echo array_search ( 'c/c++' , $array1 );
echo "\n" ;
?>
|
Example 2: The following example returns the index of an associative array.
PHP
<?php
$array1 = array (
0 => 'php' ,
1 => 'java' ,
2 => 'css/html' ,
3 => 'python' ,
4 => 'c/c++'
);
echo array_search ( 'php' , $array1 );
echo "\n" ;
echo array_search ( 'java' , $array1 );
echo "\n" ;
echo array_search ( 'c/c++' , $array1 );
echo "\n" ;
?>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...