Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove every second element from an array and rearange keys?

Tags:

arrays

php

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?

like image 995
metaforce Avatar asked Jun 29 '11 09:06

metaforce


People also ask

How do I remove every second element from an array?

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.

How do you remove every second element from an array in Python?

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.

How do I remove a specific part of an array?

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.


3 Answers

$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);
like image 158
KingCrunch Avatar answered Oct 30 '22 17:10

KingCrunch


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);
like image 27
Stefan Gehrig Avatar answered Oct 30 '22 17:10

Stefan Gehrig


Yes, of course.

for ($i = 0; $i < count($array); $i++)
{
  if (($i % 2) == 0) unset ($array[$i]);
}
like image 36
Igor Hrcek Avatar answered Oct 30 '22 18:10

Igor Hrcek