Check out array_slice() http://php.net/manual/en/function.array-slice.php
Last argument true is to preserve keys.
When you pass the offset as negative, it starts from the end. It's a nice trick to get last elements without counting the total.
$array = [
"a" => 1,
"b" => 2,
"c" => 3,
];
$lastElementWithKey = array_slice($array, -1, 1, true);
print_r($lastElementWithKey);
Outputs:
Array
(
[c] => 3
)
Answer from Mārtiņš Briedis on Stack OverflowCheck out array_slice() http://php.net/manual/en/function.array-slice.php
Last argument true is to preserve keys.
When you pass the offset as negative, it starts from the end. It's a nice trick to get last elements without counting the total.
$array = [
"a" => 1,
"b" => 2,
"c" => 3,
];
$lastElementWithKey = array_slice($array, -1, 1, true);
print_r($lastElementWithKey);
Outputs:
Array
(
[c] => 3
)
try
end($array); //pointer to end
each($array); //get pair
// first
$value = reset($arr);
$key = key($arr);
(in that order)
See reset()PHP Manual,
key()PHP Manual.
unset(
key]); # in case you want to remove it.
However array_pop()PHP Manual is working with the last element:
// last
$value = end(
key = key($arr);
unset(
key]); # in case you want to remove it.
See end()PHP Manual.
For the fun:
[$value, $key] = [reset(
arr)]; // first
[$value,
arr), key($arr)]; // last
(PHP 7.1+)
or
list($value, $key) = array(reset(
arr)); // first
list($value, $key) = array(end(
arr)); // last
(PHP 4.3+)
or
extract(array('value' => reset(
arr))); // first
extract(array('value' => end(
arr))); // last
(PHP 4.3+; Caution: extract() in use!)
or
// first
reset($arr);
list(
value) = each($arr);
// last
end($arr);
list(
value) = each($arr);
(Note: The each() function is deprecated since PHP 7.2.0 and gone since PHP 8.0.0)
or whatever style of play you like ;)
Dealing with empty arrays
It was missing so far to deal with empty arrays. So it's a need to check if there is a last (first) element and if not, set the $key to null (as null can not be an array key):
// first
for ($key = null, $value = null; false !== $_ = reset($arr);)
{
$value = $_;
unset(
key = key($arr)]);
break;
}
unset($_);
// last
for ($key = null, $value = null; false !==
arr);)
{
$value = $_;
unset(
key = key($arr)]);
break;
}
unset($_);
This will give for a filled array like $arr = array('first' => '1st', 'last' => '2nd.');:
string(4) "2nd." # value
string(4) "last" # key
array(1) { # leftover array
["first"]=>
string(3) "1st"
}
And an empty array:
bool(false) # value
NULL # key
array(0) { # leftover array
}
Afraid of using unset?
In case you don't trust unset() having the performance you need (of which I don't think it's really an issue, albeit I haven't run any metrics), you can use the native array_pop() implementation as well (but I really think that unset() as a language construct might be even faster):
// first
reset(
key = key(
value = array_pop($arr);
// last
end(
key = key(
value = array_pop($arr);
array_slice
$arr = array('k1' => 'v1', 'k2' => 'v2', 'k3' => 'v3');
$a = array_slice($arr, 0, 1);
var_dump(
arr = array_slice($arr, 1);
var_dump($arr);
array(1) {
["k1"]=>
string(2) "v1"
}
array(2) {
["k2"]=>
string(2) "v2"
["k3"]=>
string(2) "v3"
}
Try end
<?php
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
?>
Use array end So if I have an array:
$array_example = array('one', 'two', 'three');
And I want to get the last item, I can do it like this:
echo end($array_example);
That will echo out the last element of the array but will not effect the array.
After doing this, if you want to reset the internal array pointer to the first item in the array, (so you can continue working properly), just reset the array pointer:
reset($array_example);
You can use array_values for that like as
$array = [
0 => 'apple',
1 => 'banana',
2 => 'orange',
3 => 'grapes'
];
unset($array[1]);
print_r(array_values($array));
you will have to create a custom function
function removeAndreindex($array,$index)
{
unset($array[$index]);
return array_values($array)
}
Thanks
You are looking for array_shift().
PHP Array Shift
Quick Cheatsheet If you are not familiar with the lingo, here is a quick translation of alternate terms, which may be easier to remember:
* array_unshift() - (aka Prepend ;; InsertBefore ;; InsertAtBegin )
* array_shift() - (aka UnPrepend ;; RemoveBefore ;; RemoveFromBegin )
* array_push() - (aka Append ;; InsertAfter ;; InsertAtEnd )
* array_pop() - (aka UnAppend ;; RemoveAfter ;; RemoveFromEnd )
$array_fill = array(array('AAA','BBB','-','DDDD'), array(111,222,'-',444));
function clean_now($var)
{
return $var == '-'? false: true;
}
function cleanme($var)
{
return array_filter($var, "clean_now");
}
print_r(array_map("cleanme",$array_fill));
Since it's 2 dimensional array, I first use array_map to filter the array inside of each array, and array_filter to remove '-' from the array.
Try to copy my code then run it on your side. I added the variable value.
Please use unset($index); to remove an item from array
note that in above case index remains unchanged.
else
array_splice() can be used if you'd like to normalize your integer keys. Another option is using array_values() after unset()
Use array_splice():
If you're trying to remove the last n elements, use the following function:
function array_pop_n(array $arr, $n) {
return array_splice($arr, 0, -$n);
}
Demo
If you want to retrieve only the last n elements, then you can use the following function:
function array_pop_n(array $arr, $n) {
array_splice($arr,0,-$n);
return $arr;
}
Demo
It's important to note, looking at the other answers, that array_slice will leave the original array alone, so it will still contain the elements at the end, and array_splice will mutate the original array, removing the elements at the beginning (though in the example given, the function creates a copy, so the original array still would contain all elements). If you want something that literally mimics array_pop (and you don't require the order to be reversed, as it is in your OP), then do the following.
$arr = range(1, 10);
$n = 2;
$popped_array = array_slice($arr, -$n);
$arr = array_slice($arr, 0, -$n);
print_r($popped_array); // returns array(9,10);
print_r($arr); // returns array(1,2,3,4,5,6,7,8);
If you require $popped_array to be reversed, array_reverse it, or just pop it like your original example, it's efficient enough as is and much more direct.
The order of key values in an associative array don't matter. Therefore you don't need to array_push or array_unshift. The only thing you need to do is associate a key to the value you want (or vice-versa). So you would write the following to dynamically add values to the $params array.
$key = "my_id:2";
$value = "23";
$params[$key] = $value;
Yep, no shifting, or pushing... just add the $key between the square brackets and your all good.
$element = array();
$element['userclass_id'] = 3;
$element['isoline'] = 0;
$element['id:>'] = $id;
$params[] = $element