Reputation: 6277
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
Upvotes: 1
Views: 53
Reputation: 9468
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.
Upvotes: 0
Reputation: 212412
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
Upvotes: 1