I have a straight forward array with 8 values. I would like to turn it into an multidimensional array. Currently it looks like so:

array(8) {
  [0]=>
  int(0)
  [1]=>
  float(100)
  [2]=>
  int(0)
  [3]=>
  int(0)
  [4]=>
  float(0.5)
  [5]=>
  float(53.6)
  [6]=>
  float(32.8)
  [7]=>
  float(9.4)
}

Using the values above I would like the array to format like so:

array[0][0] = 0
array[0][1] = 100

array[1][0] = 0
array[1][1] = 0

array[2][0] = .5
array[2][1] = 53.6

etc.

So the goal is to create a loop that loops through and sets every 2 values to an array within an array. Any ideas?

link|improve this question

have you ever used modulus(%) $x%2=??? – Waygood yesterday
feedback

4 Answers

up vote 5 down vote accepted

I believe this is what you wanted.

$newArray = array();
for ($i=0;$i<count($originalArray);$i+=2) {
   $newArray[] = array($originalArray[$i], $originalArray[$i+1]);
}
link|improve this answer
Perfect Thanks so much! – allencoded yesterday
Up voted the array_chunk answer. It is likely more performance friendly and at the very least, easier to read and understand. – tencent yesterday
feedback

Use array_chunk to split the array every 2 elements.

This piece of code should give you exactly what you are looking for.

$newArray=array_chunk($oldArray,2,false);
link|improve this answer
+1 this is the best way. – DaveRandom yesterday
This was the way I finally have chosen as its less code and works very easily! – allencoded yesterday
feedback
$output = array();
for ($i = 0, $j = 0, $n = count($array); $i < $n; $i++) {
  $output[$j][] = $array[$i];
  if ($i % 2 == 1) {
    $j++;
  }
}

Or...

$output = array();
while ($array) {
  $output[] = array(array_shift($array), array_shift($array));
}

...and any number of variations on that theme.

link|improve this answer
feedback

Array transformation:

$a = array(0, 100, 0, 0, 0.5, 53.6, 32.8, 9.4);
$b = array();
$j=0;
foreach ($a as $i => $value) {
    if ($i%2) {
        $b[$j][1] = $value;
        $j++;
    } else {
        $b[$j][0] = $value;
    }
}
echo '<pre>';
var_export($a);
var_export($b);
echo '</pre>';
link|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.