0

Can't able to delete the empty array element in Php

//Below is my array . Notice the 1st element of the name3 array is empty and i want to remove it $arr = array( 'name' => 'Alvin', 'name2' => 'Joseph', 'name3' =>array('','abc','xyz') ) // I am using foreach loop and using unset() method , to unset that particular empty element. foreach($arr as $key =>$value) { if(is_array($value)) { foreach($value as $key1 => $val1) { if(empty($val1)) { unset($value[$key1]); } } } } echo "<pre>"; print_r($arr); The output is (The empty element with index 0 is still there:- Array ( [name] => Alvin [name2] => Joseph [name3] => Array ( [0] => [1] => abc [2] => xyz ) )

php

1/25/2019 6:37:43 AM

Saurav Kumar

1 Answer

New Answer

0

It does not work because $value from the outer foreach contains copies of the values of $arr and the inner foreach modifies these copies without any effect to the original so you can fix that by telling PHP to make &$value references to the original values stored in $arr: https://code.sololearn.com/wrsjBGLu4c0X/#php