-4

Below is a part of my produced array. How can I keep only every second element usign PHP?

I have tried this until now without luck, maybe it depends on the structure of the array, I didn't understand.

$size = count($array);
$result = array();
for ($i = 0; $i < $size; $i += 2) {
  $result[] = $array[$i];
}
var_dump($result);

this is my array below:

   Array
    (
        [0] => Array
            (
                [0] => 
                                        11.490
                [1] => 
                                        11.490
                [2] => 
                                        13.490
                [3] => 
                                        13.490
                [4] => 
                                        17.490
                [5] => 
                                        17.490
                [6] => 
                                        20.990
                [7] => 
                                        20.990
                [8] => 
                                        14.290
                [9] => 
                                        14.290
                [10] => 
                                        14.490
                [11] => 
                                        14.490
                [12] => 
                                        19.990
                [13] => 
                                        19.990
EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179

2 Answers2

0

Use array_filter (php.net)

function odd($var)
{
    return($var & 1);
}

$array[0] = array_filter($array[0], "odd", ARRAY_FILTER_USE_KEY);

EDIT:
Of course you can also use an "even" method

EDIT 2:
Change to match the code from the op.
From $array to $array[0]

EDIT 3:
Add a missing semicolon

Emaro
  • 1,397
  • 1
  • 12
  • 21
-5

How about using unset on every other element?

<?php
$array = array('1','1','2','2','4','4','5','5');

for($i = count($array) - 1; $i > 0; $i -= 2){
    unset($array[$i]);
}
Antony
  • 1,253
  • 11
  • 19
  • 1
    `array_unique` removes all duplicate, while he wants to remove only every other element. Using `array_unique` could therefore remove too many values. – Antony Jan 24 '17 at 14:11
  • 2
    But if you look at your code, it will only process HALF the array, and then reduce that by a half. So your result will be one quarter of the array – RiggsFolly Jan 24 '17 at 14:12
  • Right, fixed. Note that the new solution will only work if the array has an even number of elements. Otherwise, `$i` should start at `count($array)-2`. – Antony Jan 24 '17 at 14:18
  • 2
    `$i > 0 / 2` ? That's interesting. – yivi Jan 24 '17 at 14:19
  • 1
    Did you test it. I DID! And that does not work either. The array is unchanged – RiggsFolly Jan 24 '17 at 14:20
  • I also did :) http://sandbox.onlinephpfunctions.com/code/32bde617876abbcce738ffea6d287549d51ac673 – Antony Jan 24 '17 at 14:21