11

How can I insert values into a multidimensional array in php? I need to add more and more rows to array using a while loop.

Here is my code:

$size=10;
$p=0;
while($p<$size)
{
    $myarray = array(
        array("number"=>$data[$p],"data"=>$kkk[1],"status"=>"A"),
        array("number"=>$data[$p],"data"=>$kkk[1],"status"=>"A"));
    // Each time the loop executes, I need to add more array to myarray.
    $p++;
}
2
  • You will need something like a for($i=0;$<=$p:$i++) loop inside your while loop. Commented Sep 30, 2013 at 16:23
  • try $myarray[] = array( ... );. Might need to initialize $myarray = array(); outside of the loop, beforehand. Commented Sep 30, 2013 at 16:25

3 Answers 3

21
$size = 10;
$p = 0;
$myarray = array();
while($p < $size) {
  $myarray[] = array("number" => $data[$p], "data" => $kkk[1], "status" => "A");
  $p++;
}
Sign up to request clarification or add additional context in comments.

Comments

3
$my_array = array()
foreach (range($p, $size-1) as $key) {
    array_push($my_array, array(
        "number" => $data[$key], 
        "data" => $kkk[1], 
        "status" => "A",
    ));
}

5 Comments

Why is a foreach necessary here? The while loop would work just fine.
while does not work with range, as far as I understand it. This is only another way to do the task, more elegant, IMHO :)
Why do you need range() though?
I don't understand your question. Is there a problem with range ?
There isn't a problem, but I don't think that's necessary here, TBH.
-1
$arr = new Array();
while($p<$size){
$arr[$p]["number"] = $data[$p];
$arr[$p]["data"] = $kkk[1];
$arr[$p]["status"] = "A";

$p++;
}

Comments

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.