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.
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.
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.
You can use the PHP array_values() function to get all the values of an 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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With