Search code examples
phparraysunset

php unset foreach loop is not unsetting the value of array


I have the following code in php 7.2:

foreach ($data->certificates as $k => $certificate) {
    if (empty($certificate['testCertificateId'])) {
        unset($data->certificates[$k]);
    }
}

$data is an associative array. Each $certificate is an associative array.

If a $certificate array has no key testCertificateId, I want to remove the $certificate from $data->certificates.

I have no clue why, but this code doesn't work on php 7.2. On 7.0 it does work!

Could anyone please help? It's killing me for 2 days already...


Solution

  • This is a workaround for your current code:

    $tempArr = [];
    foreach ($data->certificates as $k => $certificate) {
        if (!empty($certificate['testCertificateId'])) {
            $tempArr[$k] = $data->certificates[$k];
        }
    }
    $data->certificates = $tempArr;