0

I am guessing I am doing this completely wrong but I want to add an array onto the end of the arrays which the foreach loop is running through.

E.g this is the start result

 array(3) {
   [0]=>
   array(1) {
   ["name"]=>
   string(7) "Matthew"
   }
  [1]=>
   array(1) {
   ["name"]=>
   string(3) "Jim"
   }
   [2]=>
  array(1) {
   ["name"]=>
    string(3) "Sam"
  }
}

This is the code im using

<?php

  $arr = array( array("name" => "Matthew"), array("name" => "Jim"), array("name" => "Sam"));

  foreach ($arr as $element) {

  $ages = array("test" => 12);

  $element['test'] = $ages;

}

?>

The desired end result

    array(3) {
   [0]=>
   array(1) {
   ["name"]=>
   string(7) "Matthew",
   array(1) {
   ["test"]=>
    int(2) 12
  }
   }
  [1]=>
   array(1) {
   ["name"]=>
   string(3) "Jim",
    array(1) {
   ["test"]=>
    int(2) 12
  }
   }
   [2]=>
  array(1) {
   ["name"]=>
    string(3) "Sam",
   array(1) {
   ["test"]=>
    int(2) 12
  }
  }
}

1 Answer 1

0

Try this

foreach ($arr as $key=>$val) {
    $ages = array("test" => 12);
    $arr[$key]['test'] = $ages;
}

result is

Array (
    [0] => Array
        (
            [name] => Matthew
            [test] => Array
                (
                    [test] => 12
                )
        )
    [1] => Array
        (
            [name] => Jim
            [test] => Array
                (
                    [test] => 12
                )
        )
    [2] => Array
        (
            [name] => Sam
            [test] => Array
                (
                    [test] => 12
                )
        ) )
0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.