php - get numeric index of associative array

PhpArrays

Php Problem Overview


I have an associative array and I need to find the numeric position of a key. I could loop through the array manually to find it, but is there a better way build into PHP?

$a = array(
  'blue'   => 'nice',
  'car'    => 'fast',
  'number' => 'none'
);
  
// echo (find numeric index of $a['car']); // output: 1

Php Solutions


Solution 1 - Php

echo array_search("car",array_keys($a));

Solution 2 - Php

$blue_keys = array_search("blue", array_keys($a));

http://php.net/manual/en/function.array-keys.php

Solution 3 - Php

While Fosco's answer is not wrong there is a case to be considered with this one: mixed arrays. Imagine I have an array like this:

$a = array(
  "nice",
  "car" => "fast",
  "none"
);

Now, PHP allows this kind of syntax but it has one problem: if I run Fosco's code I get 0 which is wrong for me, but why this happens?
Because when doing comparisons between strings and integers PHP converts strings to integers (and this is kinda stupid in my opinion), so when array_search() searches for the index it stops at the first one because apparently ("car" == 0) is true.
Setting array_search() to strict mode won't solve the problem because then array_search("0", array_keys($a)) would return false even if an element with index 0 exists.
So my solution just converts all indexes from array_keys() to strings and then compares them correctly:

echo array_search("car", array_map("strval", array_keys($a)));

Prints 1, which is correct.

EDIT:
As Shaun pointed out in the comment below, the same thing applies to the index value, if you happen to search for an int index like this:

$a = array(
  "foo" => "bar",
  "nice",
  "car" => "fast",
  "none"
);
$ind = 0;
echo array_search($ind, array_map("strval", array_keys($a)));

You will always get 0, which is wrong, so the solution would be to cast the index (if you use a variable) to a string like this:

$ind = 0;
echo array_search((string)$ind, array_map("strval", array_keys($a)));

Solution 4 - Php

The solution with array_search would be really heavy, and it's unnecessary to use straight search in this situation.

Much better solution would be:

$keyIndexOfWhichYouAreTryingToFind = 'c';
$array = [
    'a' => 'b',
    'c' => 'd'
];
$index = array_flip(array_keys($array))[$keyIndexOfWhichYouAreTryingToFind];

This type of search would have much better performance on big arrays. The reason is the difficulty, that would be O(n)=1 instead of O(n)=n (in worst of the possible variants). So for an array with 1000000 elements it would make 1 iteration instead of 1000000.

Solution 5 - Php


$a = array(
'blue' => 'nice',
'car' => 'fast',
'number' => 'none'
);

var_dump(array_search('car', array_keys($a)));
var_dump(array_search('blue', array_keys($a)));
var_dump(array_search('number', array_keys($a)));


Solution 6 - Php

All solutions based on array_keys don't work for mixed arrays. Solution is simple:

echo array_search($needle,array_keys($haystack), true);

From php.net: If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.

Solution 7 - Php

a solution i came up with... probably pretty inefficient in comparison tho Fosco's solution:

 protected function getFirstPosition(array$array, $content, $key = true) {

  $index = 0;
  if ($key) {
   foreach ($array as $key => $value) {
    if ($key == $content) {
     return $index;
    }
    $index++;
   }
  } else {
   foreach ($array as $key => $value) {
    if ($value == $content) {
     return $index;
    }
    $index++;
   }
  }
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionn00bView Question on Stackoverflow
Solution 1 - PhpFoscoView Answer on Stackoverflow
Solution 2 - PhpquantumSoupView Answer on Stackoverflow
Solution 3 - PhpXriukView Answer on Stackoverflow
Solution 4 - PhpnojitsiView Answer on Stackoverflow
Solution 5 - PhpAsteriónView Answer on Stackoverflow
Solution 6 - PhpMrBlcView Answer on Stackoverflow
Solution 7 - Phpn00bView Answer on Stackoverflow