Home > Software engineering >  PHP: Unable to resolve Warning: Undefined array key 0
PHP: Unable to resolve Warning: Undefined array key 0

Time:07-29

I want to remove all 0 values in an array, count the number of elements of array left over after they have been removed. So example:

$array = [0, 12, 3, 0, 2, 77];

I remove all the 0s and then the array count the number of elements left over.

I then want to do a calculation with the count.

I have written the code and it works pretty good - except for this one Warning I cannot get rid off Warning: Undefined array key 0 in Standard input.

Here is a link to my code that I have written: https://www.tehplayground.com/xpAM6tEISJ9NJuJD

I tried copying the array and setting it again after unset. I tried inserting the new array after the values have been removed into a new array to have it set. But the error keeps coming wherever there was a 0 value, even though it has been removed.

Any suggestions as to how I can resolve this? I feel it should not be so complicated. But it is starting to take a lot more time than expected. Thanks guys.

CodePudding user response:

You might use array_filter passing it a function that will return true only when a given number is not zero.

https://www.php.net/array-filter

Here's a demo:

https://onlinephp.io/c/6ec82

$array = [0, 12, 3, 0, 2, 77];
$filtered = array_filter($array, function($v){return $v!==0;});
$newLength = count($filtered);

var_dump($filtered);

CodePudding user response:

array_filter does that. If you don’t supply a callback function, it filters all values out that equal false (boolean conversion).

CodePudding user response:

You don't need array_icount_values at all.

foreach (array_keys($m_values, 0) as $key) {
    unset($m_values[$key]);
}

In your above snippet, since you unset the keys, they are no longer sequential. If you wish to make them sequential(since that is how you are iterating on the array in your for loop later), your snippet needs to like below using array_values:

<?php

$m_values = [0, 40, 20, 30, 0, 0];

foreach (array_keys($m_values, 0) as $key) {
    unset($m_values[$key]);
}

$m_values = array_values($m_values);

Online Demo


As an alternative, you can use a foreach loop if you wish to not worry about indexes at all like below:

<?php

if (!empty($m_values)) {
    foreach($m_values as $idx => $value){
        $sum  = $value;
    }
}

Online Demo

Tip: if(!empty($m_values)) isn't required since foreach takes care of that automatically.

Note: There are one liners to solve this specific requirement but I will keep this as is for the scope of basic learning.

  • Related