How should I remove every second element from an array like this (using nothing but the built in Array functions in PHP):
$array = array('first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh');
And when I remove every second element, I should get:
$array = array('first', 'third', 'fifth', 'seventh');
Possible?
Use Array#splice method to remove an element from the array. Where the first argument is defined as the index and second as the number elements to be deleted. To remove elements at 3rd position use a while loop which iterates in backward and then delete the element based on the position.
To remove every nth element of a list in Python, utilize the Python del keyword to delete elements from the list and slicing. For your slice, you want to pass n for the slice step size. For example, if you have a list and you to remove every 2nd element, you would delete the slice defined by [1::2] as shown below.
Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.
$array = array('first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh');
foreach (range(1, count($array), 2) as $key) {
unset($array[$key]);
}
$array = array_merge($array);
var_dump($array);
or
$array = array('first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh');
$size = count($array);
$result = array();
for ($i = 0; $i < $size; $i += 2) {
$result[] = $array[$i];
}
var_dump($result);
Another approach using array_intersect_key
:
$array = array('first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh');
$keys = range(0, count($array), 2);
$result = array_values(array_intersect_key($array, array_combine($keys, $keys)));
var_dump($result);
Yes, of course.
for ($i = 0; $i < count($array); $i++)
{
if (($i % 2) == 0) unset ($array[$i]);
}
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