0

I have an array. I want to check its elements' values and change them if they are equal to 0 or 0.00

Here's what i tried and failed :

foreach($returnArray as $arrayElement){
            if($arrayElement === 0 || $arrayElement === 0.00){
                $arrayElement = null;
            }
        }

I wanna change 0 or 0.00 values into null value. $returnArray is my main array, it has some int and double values.

0

4 Answers 4

3

You could use array_map(), and just test each element for a falsey value (both 0 and 0.00 equate to false):

$returnArray = array_map(function($a) { return $a ?: null; }, $returnArray);

Here's an example

Sign up to request clarification or add additional context in comments.

Comments

2

There is only one mistake, $arrayElement = null; has scope only within the loop. You need

foreach($returnArray as $key=>$arrayElement){
            if($arrayElement == 0 ){
                $returnArray[$key] = null; // This updates the actual array
            }
        }

This way you update the actual array elements which will stay that way even after the loop. Using the temporary variable within the loop will not have changes visible outside it.

Comments

2

PHP passes elements into foreach loops as copies. You can pass the actual element by refence like this:

foreach($returnArray as &$arrayElement){
    if($arrayElement === 0 || $arrayElement === 0.00){
        $arrayElement = null;
    }
}

2 Comments

can you enlighten me what do you mean by loops as copies ?
See my update. When using a foreach you are using a copy of the value with a local scope inside the loop.
1

And with:

foreach($returnArray as $k => $arrayElement){
            if($arrayElement <= 0){
                $returnArray[$k] = null;
            }
        }

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.