PHP: Get n-th item of an associative array

Nick Heiner picture Nick Heiner · Jan 4, 2010 · Viewed 62.2k times · Source

If you have an associative array:

Array
(
    [uid] => Marvelous
    [status] => 1
    [set_later] => Array
        (
            [0] => 1
            [1] => 0
        )

    [op] => Submit
    [submit] => Submit
)

And you want to access the 2nd item, how would you do it? $arr[1] doesn't seem to be working:

foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
    if (! $setLater) {
        $valueForAll = $form_state['values'][$fieldKey];
        $_SESSION[SET_NOW_KEY][array_search($valueForAll, $form_state['values'])] = $valueForAll; // this isn't getting the value properly
    }
}

This code is supposed to produce:

$_SESSION[SET_NOW_KEY]['status'] = 1

But it just produces a blank entry.

Answer

nickf picture nickf · Jan 4, 2010

Use array_slice

$second = array_slice($array, 1, 1, true);  // array("status" => 1)

// or

list($value) = array_slice($array, 1, 1); // 1

// or

$blah = array_slice($array, 1, 1); // array(0 => 1)
$value = $blah[0];