1

I want to return both the key and value of an array item, from only knowing their numerically ordered number.

Is there a better method than using these two functions?

$num = '3';
$array = [
        'fish' => 'blue',
        'monkey' => 'green',
        'pig' => 'blue',
        'cat' => 'yellow',
];

echo array_values($array)[$num]; // yellow
echo array_keys($array)[$num]; // cat
Andy G
  • 19,232
  • 5
  • 47
  • 69
ditto
  • 5,917
  • 10
  • 51
  • 88
  • No, there isn't. You could wrap those two in your own function to return both values at once... – scrowler Jun 02 '14 at 22:47
  • No, that's about the simplest way to do it. You could iterate over the array & count items, but that's just making it more complicated. – Kryten Jun 02 '14 at 22:48

2 Answers2

1

Sure, array_slice()

$num = '3';
$array = [
        'fish' => 'blue',
        'monkey' => 'green',
        'pig' => 'blue',
        'cat' => 'yellow',
];


$newArray = array_slice($array, $num, 1);
var_dump($newArray);

works perfectly well for associative arrays

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

Here's an option with a foreach loop

$count = 0;
foreach ($array as $key => $value){
     if($count == 3){
          echo $key.' '.$value;
     }
     $count++;
}

But your current method is probably better.

Dan
  • 9,391
  • 5
  • 41
  • 73