PHP: Get n-th item of an associative array PHP: Get n-th item of an associative array php php

PHP: Get n-th item of an associative array


Use array_slice

$second = array_slice($array, 1, 1, true);  // array("status" => 1)// orlist($value) = array_slice($array, 1, 1); // 1// or$blah = array_slice($array, 1, 1); // array(0 => 1)$value = $blah[0];


I am a bit confused. Your code does not appear to have the correct keys for the array. However, if you wish to grab just the second element in an array, you could use:

$keys = array_keys($inArray);$key = $keys[1];$value = $inArray[$key];

However, after considering what it appears you're trying to do, something like this might work better:

$ii = 0;$setLaterArr = $form_state['values']['set_later'];foreach($form_state['values'] as $key => $value) {    if($key == 'set_later')        continue;    $setLater = $setLaterArr[$ii];    if(! $setLater) {        $_SESSION[SET_NOW_KEY][$key] = $value;    }    $ii ++;}

Does that help? It seems you are trying to set the session value if the set_later value is not set. The above code does this. Instead of iterating through the inner array, however, it iterates through the outer array and uses an index to track where it is in the inner array. This should be reasonably performant.


You can use array_slice to get the second item:

$a= array( 'hello'=> 'world', 'how'=> 'are you', 'an'=> 'array',);$second= array_slice($a, 1, 1, true);var_dump($second);