1
$i=0;
$array=array("one","two");
foreach($array as &$point)
{
   $point[$i]=array($point[$i], $i);
   $i++;
}

var_dump($array);

yields:

array(2) { [0]=> string(3) "Ane" [1]=> &string(3) "tAo" }

I was expecting something more like:

[0]=> [0]=> "one" [1]= 1
[1]=> [0]=> "two" [1]= 2

Am I doing the inner block of the foreach wrong, or is there another method I should be using to go from a single to a 2D array?

3 Answers 3

1

You mean like this:

$i=1;
$array=array("one","two");
foreach($array as $j => $point)
{
   $array[$j]=array($point, $i);
   $i++;
}

var_dump($array);

Outputs:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(3) "one"
    [1]=>
    int(1)
  }
  [1]=>
  array(2) {
    [0]=>
    string(3) "two"
    [1]=>
    int(2)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1
$array = array("one","two");
foreach($array as $i => &$point)
{
   $point = array($point, $i + 1);
}

var_dump($array);

There were several errors in your code:

  1. You should assign to $point
  2. You should access $point, not $point[$i]
  3. If you had error output turned on (or of you look at the error logs) you'd see Array to string conversion error for your code.

Comments

0

You may use this to define a two dimensional array in PHP

$array = array(
  array(0, 1, 2),
  array(3, 4, 5),
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.