skip to Main Content

I have this PHP array:-

$tblData[] = array(
    "Orange" => "Healthy",
    "Apple" => "Good",
    "Pizza" => "Bad",
);

This is the output:-

Array
(
    [0] => Array
        (
            [Orange] => Healthy
            [Apple] => Good
            [Pizza] => Bad
        )

)

Now, if I add this:-

$tblData[] = array(
    "Hot dogs" => "Big No",
);

This is the output:-

Array
(
    [0] => Array
        (
            [Orange] => Healthy
            [Apple] => Good
            [Pizza] => Bad
        )

    [1] => Array
        (
            [Hot dogs] => Big No
        )

)

I want the new key value pair, i.e., "Hot dogs" => "Big No" to be added under "Pizza" => "Bad" i.e., under the index [0] as an item, like this:-

Array
(
    [0] => Array
        (
            [Orange] => Healthy
            [Apple] => Good
            [Pizza] => Bad
            [Hot dogs] => Big No
        )

)

I have tried specifying the index, tried array_push and array_merge. But, I can’t get it right.

3

Answers


  1. That’s because you have an array inside another array. What you’re doing is adding an element to the outer array, you wish to add it to the inner. You reach the inner array using $tblData[0], so what you need to do is:

    $tblData[0][] = array("Hot dogs" => "Big No");
    
    Login or Signup to reply.
  2. You could use any of these methods below in the code, and maybe others also.

    Uncomment one of the lines below and test them

    $tblData[] = array(
        "Orange" => "Healthy",
        "Apple" => "Good",
        "Pizza" => "Bad",
    );
    
    
    #$tblData[0] += array("Hot dogs" => "Big No");
    #$tblData = array_merge($tblData[0], array("Hot dogs" => "Big No"));
    
    print_r($tblData);
    

    They will all generate

    Array
    (
        [Orange] => Healthy
        [Apple] => Good
        [Pizza] => Bad
        [Hot dogs] => Big No
    )
    
    Login or Signup to reply.
  3. You’re currently adding the new entry into the outer array. You need to add it to the inner one (situated at index 0 of the outer array). To do that, simply specify the index of the outer array you want to write to:

    $tblData[0]["Hot dogs"] = "Big No";
    

    Live demo: https://3v4l.org/gcfnI

    N.B. This is just one approach, there are several ways to solve it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search