Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of a certain value in an array in PHP

Tags:

arrays

php

I have an array:

$list = array('string1', 'string2', 'string3'); 

I want to get the index for a given value (i.e. 1 for string2 and 2 for string3)

All I want is the position of the strings in the array

  • string1 is 0
  • string2 is 1
  • string3 is 2

How to achieve this?

like image 545
Aakash Chakravarthy Avatar asked Jun 02 '10 15:06

Aakash Chakravarthy


People also ask

How do you find a specific value in an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

Where can I find index PHP?

Follow the path wp-content > themes. Open your theme folder. In that you can see index. php file.


1 Answers

array_search is the way to do it.

array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

From the docs:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');  $key = array_search('green', $array); // $key = 2; $key = array_search('red', $array);   // $key = 1; 

You could loop over the array manually and find the index but why do it when there's a function for that. This function always returns a key and it will work well with associative and normal arrays.

like image 89
RaYell Avatar answered Oct 05 '22 15:10

RaYell