Wednesday, July 3, 2024
HomeLanguagesPhpHow to find the index of an element in an array using...

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




<?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




<?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

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments