0

I have an array that looks like this:

$array = array("a", "b", 0, "c", 0);

How can I remove all elements with 0 and shift the index of the remaining elements?

I want the result to be like this:

Array ( [0] => a [1] => b [2] => c )

I tried this but it didn't work:

array_diff($bal_units, array(0));
OMi Shah
  • 5,768
  • 3
  • 25
  • 34
  • call ``array_values`` on the result to reset the index. as: ``array_values(array_diff($bal_units, array(0)))`` https://3v4l.org/f75rN – OMi Shah Jan 03 '23 at 12:11
  • Duplicate of https://stackoverflow.com/questions/3109098/how-to-reset-indexes-in-array-diff-result – OMi Shah Jan 03 '23 at 12:12
  • 2
    `$array = array_filter($array)` – shingo Jan 03 '23 at 12:14
  • Does this answer your question? [How to remove duplicate values from an array in PHP](https://stackoverflow.com/questions/307650/how-to-remove-duplicate-values-from-an-array-in-php) – nice_dev Jan 03 '23 at 12:40

1 Answers1

-1
//input

$array = array("a", "b", 0, "c", 0);

$array = array_diff($array, array(0));

if (($key = array_search(0, $array)) !== false) {

    array_splice($array, $key, 0);
}

print_r($array);

RESULT

Array ( [0] => a [1] => b [2] => c )
Noruzzaman
  • 11
  • 7
  • 2
    But that is an exact copy of what the OP have already tried. And, as the OP said, it indeed doesn't work (index 2 is not element "c"). – chrslg Jan 04 '23 at 00:33
  • I made some code updates. It is currently working in accordance with the specifications. – Noruzzaman Jan 04 '23 at 05:27