tags:

views:

123

answers:

4

I got an associative array and I need to find the numeric position of a key. I could loop through to find it but 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
+3  A: 
$blue_keys = array_search("blue", array_keys($a));

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

quantumSoup
+8  A: 
echo array_search("car",array_keys($a));
Fosco
awesome, thank you so much.
n00b
A: 

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++;
   }
  }
 }
n00b
Yeah, PHP has thousands of builtin functions for a reason. These are *usually* much faster than equivalent logic written out the long way in PHP code.
Bill Karwin
A: 

  $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)));