[ACCEPTED]-Remove every second element from an array and rearange keys?-arrays

Accepted answer
Score: 17
$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);

0

Score: 3

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);

0

Score: 1

Yes, of course.

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

0

Score: 0

The correct way is a reverse-loop(along 2 with the usual modulus) For anyone looking 1 for a copy and paste solution:

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

More Related questions