Delete every second element from an array and regrouping keys?

How to remove every second element from such an array (using only the built-in Array functions in PHP):

$array = array('first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh');

And when I delete every second element, I should get:

$array = array('first', 'third', 'fifth', 'seventh');

Possible?

+5
source share
4 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);
+14
source

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);
+3
source

Yes of course.

for ($i = 0; $i < count($array); $i++)
{
  if (($i % 2) == 0) unset ($array[$i]);
}
+1
source

The right way is the return loop (along with the regular module) For those who are looking for a solution for copy and paste:

for ($i = count($ar)-1; $i >= 0 ; $i--){ if (($i % 2) == 0) unset ($ar[$i]); }

0
source

All Articles