saimcan
saimcan

Reputation: 1762

How to change array values using php

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.

Upvotes: 0

Views: 50

Answers (4)

billyonecan
billyonecan

Reputation: 20270

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

Upvotes: 3

Jørgen R
Jørgen R

Reputation: 10806

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;
    }
}

Upvotes: 2

Imaginaerum
Imaginaerum

Reputation: 779

And with:

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

Upvotes: 1

Hanky Panky
Hanky Panky

Reputation: 46900

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.

Upvotes: 2

Related Questions