PHP - How to get the element before the last element from an array?

PhpArraysElement

Php Problem Overview


How can I get the element before the last element from an array in PHP5 ?

Php Solutions


Solution 1 - Php

This will work even on this array:

$array[0] = "hello";
$array[5] = "how";
$array[9] = "are";

end($array);
echo prev($array); // will print "how"

The other solutions using count() are assuming that the indexes of your array go in order; by using end and prev to move the array pointer, you get the actual values. Try using the count() method on the array above and it will fail.

Solution 2 - Php

$array[count($array)-2]

It should be a numerically indexed array (from zero). You should have at least 2 elements for this to work. (obviously)

Solution 3 - Php

array_slice takes a negative offset as the second argument. This will give you a single item array containing the second last item:

$arr = array(1,2,3,4,5,6);
array_slice($arr, -2, 1);

If you just want the single value on it's own you have several options. If you don't mind using an intermediate variable you can then just get the first value with [0] or call array_pop or array_shift, they both need a variable passed by reference or you'll get warnings in strict mode.

Or you could just use array_sum or array_product, which is a bit hacky but works fine for single item arrays.

Solution 4 - Php

A method that will work for both associative array and numeric array is to use array_pop() to pop the element off the end of array.

$last = array_pop($array);
$second_last = array_pop($array);

// put back the last
array_push($array, $last);

Solution 5 - Php

All arrays have an "internal array pointer" which points to the current array element, PHP has several functions which allow you to navigate through the array and view the current elements key and value.

  • end() - Set the internal pointer of an array to its last element
  • reset() - Set the internal pointer of an array to its first element
  • prev() - Rewind the internal array pointer
  • next() - Advance the internal array pointer of an array
  • current() - Return the current element in an array
  • key() - Fetch a key from an array
  • each() - Return the current key and value pair from an array and advance the array cursor

These functions work whether the array is empty, sequential or associative and as an array has not been specified in the example i've assumed this must work with any array.

$array = array(
	'before_last' => false,
	'last' => false,
);

end($array); /* 
- set pointer to last element -> $array['last']
- return new current element value if it exists, -> false
- else return FALSE 
*/

prev($array); /* 
- set pointer one place before current pointer -> $array['before_last']
- return new current element value if it exists, -> false
- else return FALSE 
*/

if(!is_null(key($array)){ /* 
- return current element key if it exists -> "before_last"
- else return NULL
*/
    $before_last_element_value = current($array); /* 
    - return current element value if it exists, -> false
    - else return FALSE 
    */
}

As you can see the expected result (false) and the result for a nonexistent element is the same (FALSE) so you cannot check whether an element exists using the returned element value, an element key is different.

> The key can either be an integer or a string. The value can be of any type. source

The key() returns the value of the current key if the element exists otherwise it will return NULL. A valid key can never be NULL so if null is returned we can determine that the element does not exist.

Solution 6 - Php

// Indexed based array
$test = array('a','b','c','d','e');
$count = count($test);
print $test[$count-2];

// Associative Array
$months = array(
         'jan'=>'January', 
         'feb' => 'february', 
         'mar' => 'March', 
         'apr' => 'April'
    );

$keys = array_keys($months);
$count = count($keys);
print $keys[$count-2];

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
QuestionManny CalaveraView Question on Stackoverflow
Solution 1 - PhpErikView Answer on Stackoverflow
Solution 2 - PhpNotinlistView Answer on Stackoverflow
Solution 3 - PhpJames WheareView Answer on Stackoverflow
Solution 4 - PhpYadaView Answer on Stackoverflow
Solution 5 - PhpTarranJonesView Answer on Stackoverflow
Solution 6 - PhpDarshanaView Answer on Stackoverflow