Nick Heiner Nick Heiner - 3 years ago 179
PHP Question

PHP: Get n-th item of an associative array

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 Source

Use array_slice

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

// or

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

// or

$blah = array_slice($array, 1, 1, true); // array(0 => 1)
$value = $blah[0];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download