Search code examples
phpforeachunset

How to reset array index after unset key in foreach loop in php?


I am using unset to remove the particular object from the array with my conditions. But after unset, I am getting an object rather than an array. I tried to use array_values to rearrange the index, but it's not working for me. Please help me to resolve this issue. Below is my code:

$empId = '100'; //just for example.
foreach($jsonData['data'] => $key as $value){
    if($value['emp_id'] == $empId){
        unset($jsonData['data][$key]);
    }
}
after loop code//
return $jsonData;

after unset data, it gives me an object. I tried with array_values, array_merge but it's not working for me. I tried to replace array_splice with unset, but it's not removing data.


Solution

  • key emp_id is as string, not as index. your code has unset emp_id. alternatively, you may use array_map function and then use array_values to reindex your array.