Search code examples
phplaraveldd

DD does not work in the nested foreach loop


I am trying to see whats in the variable. It is a multiple nested foreach. Up to a certain point in the foreach it is able to output the dd. Then suddenly it does'nt work anymore, it seems as if Laravel is reading over it.

I have tried with var_dump and that is not working either. If I type random words it does throw error on them, so the code does get there.

The code:

foreach ($houses as $house) {
        foreach ($house['forms'] as $form) {
            echo 'Hello World';
            foreach ($projectForms['forms'] as $addedForm) {
                dd($form); //This is the dump I would like to see
                if($addedForm['id'] === $form['id']) {
                    array_push($addedForm['streets'], $house['fullStreet']);
                } else {
                    array_push($projectForms['forms'], array('id' => $form['id'], 'name' => $form['name'], 'percentage' => $form['percentage'], 'streets' => $house['fullStreet']));

                }
            }
        }
    }

dd $houses:

array:3 [▼
  0 => array:3 [▼
    "id" => 97641
    "fullStreet" => "SomeStreet 1"
    "forms" => array:1 [▼
      0 => array:3 [▼
        "id" => 2456
        "name" => "Some Name"
        "percentage" => 6.6666666666667
      ]
    ]
  ]
  1 => array:3 [▼
    "id" => 97642
    "fullStreet" => "SomeStreet 2"
    "forms" => array:1 [▼
      0 => array:3 [▼
        "id" => 2456
        "name" => "Some Name"
        "percentage" => 6.6666666666667
      ]
    ]
  ]
  2 => array:3 [▼
    "id" => 97643
    "fullStreet" => "SomeStreet 3"
    "forms" => array:1 [▼
      0 => array:3 [▼
        "id" => 2456
        "name" => "Some Name"
        "percentage" => 6.6666666666667
      ]
    ]
  ]
]

dd $form:

array:3 [▼
    "id" => 2456
    "name" => "Some Name"
    "percentage" => 6.6666666666667
]

dd $projectForms:

array:2 [▼
  "projectName" => "Some Project Name"
  "forms" => []
]

I am wondering why the dd is not working in the foreach for the $projectForms. Under the echo above it, it does work.


Solution

  • You should check first data exist in array like: !empty()

    foreach ($houses as $house) {
        if(!empty($house['forms']){
            foreach ($house['forms'] as $form) {
                if(!empty($projectForms['forms']){
                    foreach ($projectForms['forms'] as $addedForm) {
                        dd($form); //This is the dump I would like to see
                        if($addedForm['id'] === $form['id']) {
                            array_push($addedForm['streets'], $house['fullStreet']);
                        } else {
                            array_push($projectForms['forms'], array('id' => $form['id'], 'name' => $form['name'], 'percentage' => $form['percentage'], 'streets' => $house['fullStreet']));
    
                        }
                    }
                }
            }
        }
    }