ditto
ditto

Reputation: 6277

Return array key and value from ordered number

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

Answers (2)

Dan
Dan

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

Mark Baker
Mark Baker

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

Related Questions