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"
}
There are different ways to delete an array element, where some are more useful for some specific tasks than others.
Deleting a Single Array Element
If you want to delete just one single array element you can use unset() and alternatively array_splice().
By key or by value?
If you know the value and don't know the key to delete the element you can use array_search() to get the key.
This only works if the element doesn't occur more than once, since array_search() returns the first hit only.
unset() Expression
Note: When you use unset() the array keys won’t change.
If you want to reindex the keys you can use array_values() after unset(),
which will convert all keys to numerically enumerated keys starting from 0
(the array remains a list).
Example Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
// ↑ Key of element to delete
Example Output:
[
[0] => a
[2] => c
]
array_splice() Function
If you use array_splice() the (integer) keys will automatically be reindex-ed,
but the associative (string) keys won't change — as opposed to array_values() after unset(),
which will convert all keys to numerical keys.
Note: array_splice()
needs the offset, not the key, as the second parameter; offset = array_flip(array_keys(array))[key].
Example Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
array_splice($array, 1, 1);
// ↑ Offset of element to delete
Example Output:
[
[0] => a
[1] => c
]
array_splice(), same as unset(), take the array by reference. You don’t assign the return values back to the array.
Deleting Multiple Array Elements
If you want to delete multiple array elements and don’t want
to call unset() or array_splice() multiple times you can use the functions array_diff() or
array_diff_key() depending on whether you know the values or the keys of the elements to remove from the array.
array_diff() Function
If you know the values of the array elements which you want to delete, then you can use array_diff().
As before with unset() it won’t change the keys of the array.
Example Code:
$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = array_diff($array, ["a", "c"]);
// └────────┘
// Array values to delete
Example Output:
[
[1] => b
]
array_diff_key() Function
If you know the keys of the elements which you want to delete, then you want to use array_diff_key().
You have to make sure you pass the keys as keys in the second parameter and not as values.
Keys won’t reindex.
Example Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = array_diff_key($array, [0 => "xy", "2" => "xy"]);
// ↑ ↑
// Array keys of elements to delete
Example Output:
[
[1] => b
]
If you want to use unset() or array_splice() to delete multiple elements with the same value you can use
array_keys() to get all the keys for a specific value
and then delete all elements.
array_filter() Function
If you want to delete all elements with a specific value in the array you can use array_filter().
Example Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = array_filter($array, static function ($element) {
return $element !== "b";
// ↑
// Array value which you want to delete
});
Example Output:
[
[0] => a
[2] => c
]
It should be noted that unset() will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:
$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[3]=>
int(3)
} */
$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
So array_splice() can be used if you'd like to normalize your integer keys. Another option is using array_values() after unset():
$array = array(0, 1, 2, 3);
unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
} */
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