[php] Get the index of a certain value in an array in 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?

This question is related to php arrays

The answer is


$find="Topsite";
$list=array("Tope","Ajayi","Topsite","Infotech");
$list_count=count($list);
sort($list);
for($i=0;$i<$list_count;$i++)
{
    if($list[$i]==$find){
         $position=$i;
    }

}
echo $position;

Could you be a little more specific?

$key = array_search('string2',$list)

works fine for me. Are you trying to accomplish something more complex?


You'll have to create a function for this. I don't think there is any built-in function for that purpose. All PHP arrays are associative by default. So, if you are unsure about their keys, here is the code:

<?php

$given_array = array('Monday' => 'boring',
'Friday' => 'yay',
'boring',
'Sunday' => 'fun',
7 => 'boring',
'Saturday' => 'yay fun',
'Wednesday' => 'boring',
'my life' => 'boring');

$repeating_value = "boring";

function array_value_positions($array, $value){
    $index = 0;
    $value_array = array();
        foreach($array as $v){
            if($value == $v){
                $value_array[$index] = $value;
            }
        $index++;
        }
    return $value_array;
}

$value_array = array_value_positions($given_array, $repeating_value);

$result = "The value '$value_array[0]' was found at these indices in the given array: ";

$key_string = implode(', ',array_keys($value_array));

echo $result . $key_string . "\n";//Output: The value 'boring' was found at these indices in the given array: 0, 2, 4, 6, 7


// or considering your array structure:

$array = array(
  'string1' => array('a' => '', 'b' => '', 'c' => ''),
  'string2' => array('a' => '', 'b' => '', 'c' => ''),
  'string3' => array('a' => '', 'b' => '', 'c' => ''),
);

// you could just

function findIndexOfKey($key_to_index,$array){
  return array_search($key_to_index,array_keys($array));
}

// executed

print "\r\n//-- Method 1 --//\r\n";
print '#index of: string1 = '.findIndexofKey('string1',$array)."\r\n";
print '#index of: string2 = '.findIndexofKey('string2',$array)."\r\n";
print '#index of: string3 = '.findIndexofKey('string3',$array)."\r\n";

// alternatively

print "\r\n//-- Method 2 --//\r\n";
print '#index of: string1 = '.array_search('string1',array_keys($array))."\r\n";
print '#index of: string2 = '.array_search('string2',array_keys($array))."\r\n";
print '#index of: string3 = '.array_search('string3',array_keys($array))."\r\n";

// recursersively

print "\r\n//-- Method 3 --//\r\n";
foreach(array_keys($array) as $key => $value){
  print '#index of: '.$value.' = '.$key."\r\n";
}

// outputs

//-- Method 1 --//
#index of: string1 = 0
#index of: string2 = 1
#index of: string3 = 2

//-- Method 2 --//
#index of: string1 = 0
#index of: string2 = 1
#index of: string3 = 2

//-- Method 3 --//
#index of: string1 = 0
#index of: string2 = 1
#index of: string3 = 2

Try the array_keys PHP function.

$key_string1 = array_keys($list, 'string1');

Here is a function that will work for numeric or string indices. Pass the array as first parameter, then the index to the element that needs to be moved and finally set the direction to -1 to move the element up and to 1 to move it down. Example: Move(['first'=>'Peter','second'=>'Paul','third'=>'Kate'],'second',-1) will move Paul up and Peter down.

function Move($a,$element,$direction)
{

$temp = [];
$index = 0;

foreach($a as $key=>$value)
{
    $temp[$index++] = $key;
}

$index = array_search($element,$temp);

$newpos = $index+$direction;

if(isset($temp[$newpos]))
{
        $value2 = $temp[$newpos];
        $temp[$newpos]=$element;
        $temp[$index]=$value2;
}
else
{
    # move is not possible
    return $a; # returns the array unchanged
}   

$final = [];

foreach($temp as $next)
{
    $final[$next]=$a[$next];
}

return $final;

}


This code should do the same as your new routine, working with the correct multi-dimensional array..

 $arr = array(
  'string1' => array('a' => '', 'b' => '', 'c' => ''),
  'string2' => array('a' => '', 'b' => '', 'c' => ''),
  'string3' => array('a' => '', 'b' => '', 'c' => '')
 );

 echo 'Index of "string2" = '. array_search('string2', array_keys($arr));

The problem is that you don't have a numerical index on your array.
Using array_values() will create a zero indexed array that you can then search using array_search() bypassing the need to use a for loop.

$list = ['string1', 'string2', 'string3'];
$index = array_search('string2',array_values($list));

If you're only doing a few of them (and/or the array size is large), then you were on the right track with array_search:

$list = array('string1', 'string2', 'string3');
$k = array_search('string2', $list); //$k = 1;

If you want all (or a lot of them), a loop will prob do you better:

foreach ($list as $key => $value) {
    echo $value . " in " . $key . ", ";
}
// Prints "string1 in 0, string2 in 1, string3 in 2, "

Other folks have suggested array_search() which gives the key of the array element where the value is found. You can ensure that the array keys are contiguous integers by using array_values():

$list = array(0=>'string1', 'foo'=>'string2', 42=>'string3');
$index = array_search('string2', array_values($list));
print "$index\n";

// result: 1

You said in your question that array_search() was no use. Can you explain why? What did you try and how did it not meet your needs?


array_search should work fine, just tested this and it returns the keys as expected:

$list = array('string1', 'string2', 'string3');
echo "Key = ".array_search('string1', $list);
echo " Key = ".array_search('string2', $list);
echo " Key = ".array_search('string3', $list);

Or for the index, you could use

$list = array('string1', 'string2', 'string3');
echo "Index = ".array_search('string1', array_merge($list));
echo " Index = ".array_search('string2', array_merge($list));
echo " Index = ".array_search('string3', array_merge($list));