Search code examples
phparraysarray-key

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

Solution

  • 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