Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 899
Nick Heiner Avatar asked Jan 04 '10 05:01

Nick Heiner


People also ask

How do you access the elements of an associative array?

The elements of an associative array can only be accessed by the corresponding keys. As there is not strict indexing between the keys, accessing the elements normally by integer index is not possible in PHP. Although the array_keys() function can be used to get an indexed array of keys for an associative array.

How do you find the nth element of an array?

If you want to access the nth element without knowing the index, you can use next() n times to reach the nth element. for($i = 0; $i<$n; $i++){ $myVal = next(); } echo $myVal; There are other ways to access a specific element, already mentioned by @deceze.

How can we access a specific value in an associative array in PHP?

You can use the PHP array_values() function to get all the values of an associative array.

Does In_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.


1 Answers

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]; 
like image 96
nickf Avatar answered Sep 22 '22 04:09

nickf