1

I have an array with keys and values. The Keys are always set, the values might be "0" or NULL. What I want to do: Add all key-value-pairs which have a value into a new array. I use !empty() for this. Problem is: This loop also adds keys to the new array which contain NULL or "0".

Here is my code:

    // Loop over array and find all vars which are not empty
    $i = 0;
    foreach ($allInfoArray as $aKey=>$aVal) {
        if (!empty($aKey[$i])) {
            $relevantInfoArray[$aKey] = $aVal;
        }
        $i++;
    }

After that I uses var_dump() to check the new array.

array(11) { ["Key1"]=> string(3) "yes" ["Key2"]=> string(4) "1010" ["Key3"]=> string(4) "DED1" ["Key4"]=> string(7) "1234567" ["Group"]=> string(0) "" ["Dim"]=> string(0) "" ["Grd"]=> string(0) "" ["Nrm"]=> string(0) "" ["Flmc"]=> NULL ["Trmc"]=> NULL ["TrDim"]=> string(0) "" }

As you can see, the last values are all 0 or NULL. This also seems to happen randomly, other keys which have the value NULL or 0 are not added to this array.

Any ideas why these keys are added to the new array? Thanks a lot :)

2
  • @Jeff I thought so too, but it really seemed like a lot fewer values would have ended up in the result. Commented May 31, 2017 at 18:08
  • You should have checked for $aVal Commented May 31, 2017 at 18:12

1 Answer 1

3

This doesn't answer why it isn't working, but it looks like you should be able to just use array_filter for this.

$relevantInfoArray = array_filter($allInfoArray);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.