5

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?

metaforce
  • 1,337
  • 5
  • 17
  • 26

4 Answers4

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);
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
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);
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
1

Yes, of course.

for ($i = 0; $i < count($array); $i++)
{
  if (($i % 2) == 0) unset ($array[$i]);
}
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
Igor Hrcek
  • 715
  • 5
  • 16
  • 1
    This will not rearrange the keys and (according the question) this will remove 0,2,4 , ..., but they should be kept. 1,3,5, ... should be removed. A minor "thing": You shouldn't use functions in a `for`-test-expression, because it get called in any iteration. Additional it will lead to unwanted behavior, because the size of the array changes (after the first `unset()` the size is not `$maxKey + 1` anymore). – KingCrunch Jun 29 '11 at 10:05
  • @KingCrunch I just was giving him an example. Also I agree with using functions in a for-test-expression. But once again, this is just a school example how he should think in order to solve his problem. – Igor Hrcek Jun 29 '11 at 10:11
  • THIS ANSWER IS WRONG, as KingCrunch stated, this will utterly mutilate an array. See my answer below. – iautomation Sep 21 '15 at 22:08
  • if you "count" array each time in loop you will get wrong calculated value each "for" loop – zoore Nov 30 '18 at 03:55
0

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

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

iautomation
  • 996
  • 10
  • 18