PHP: Get n-th item of an associative array

PhpAssociative Array

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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];

Solution 2 - Php

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.

Solution 3 - Php

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);

Solution 4 - Php

Here's a one line way to do it with array_slice and current

$value = current(array_slice($array, 1, 1)); // returns value only

Solution 5 - Php

If the array you provide in the first example corresponds to $form_state then

$form_state['values']['set_later'][1]

will work.

Otherwise

$i = 0;
foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
    if ($i == 1) {
        $valueForAll = $form_state['values'][$fieldKey];
        $_SESSION[SET_NOW_KEY][$fieldKey] = $setLater;
        continue;
    }
	$i++;
}

Solution 6 - Php

Every one of the responses here are focused on getting the second element, independently on how the array is formed.

If this is your case.

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

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

Then you can get the value of the second element via $array['status'].

Also this code

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
    }
}

I don't understand what are you trying to do, care to explain?

Solution 7 - Php

/**
		 * Get nth item from an associative array
		 * 
		 * 
		 * @param     $arr
		 * @param int $nth
		 *
		 * @return array
		 */
		function getNthItemFromArr($arr, $nth = 0){
			$nth = intval($nth);
			if(is_array($arr) && sizeof($arr) > 0 && $nth > 0){
				$arr = array_slice($arr,$nth-1, 1, true);
			}
			return $arr;
		}//end function getNthItemFromArr

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick HeinerView Question on Stackoverflow
Solution 1 - PhpnickfView Answer on Stackoverflow
Solution 2 - PhpPerry MungerView Answer on Stackoverflow
Solution 3 - PhpleepowersView Answer on Stackoverflow
Solution 4 - PhpSam CarltonView Answer on Stackoverflow
Solution 5 - PhpElise van LooijView Answer on Stackoverflow
Solution 6 - PhpmetrobalderasView Answer on Stackoverflow
Solution 7 - PhpManchumaharaView Answer on Stackoverflow