How should I remove every second element from an array like this (using nothing but the built 开发者_如何学Pythonin 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?
$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]);
}
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]);
}
精彩评论