MANOJ
MANOJ

Reputation: 187

PHP multidimensional array value replace with another value

I have an array as below

Array
(
    [0] => Array
        (
            [0] => Pedigree Dry
            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

    [1] => Array
        (
            [0] => Professional Range
            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

    [2] => Array
        (
            [0] => Pedigree Wet
            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

    [3] => Array
        (
            [0] => PMM
            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

    [4] => Array
        (
            [0] => Chappi
            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

    [5] => Array
        (
            [0] => Care & Treat
            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

    [6] => Array
        (
            [0] => Sheba
            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

    [7] => Array
        (
            [0] => Whiskas Dry
            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

    [8] => Array
        (
            [0] => Whiskas Wet
            [1] => N/A
            [2] => N/A
            [3] => N/A
        )

)

The above code is an multidimensional array.But all array elements(except index) is N/A.I want to replace all the N/A with 0. How can I replace all N/A with 0 ?

Upvotes: 0

Views: 3546

Answers (3)

Ali
Ali

Reputation: 3461

$newArray = array();    
foreach($array as $inner_array) {
    $newArray[] = str_replace("N/A", 0, $inner_array);
}

This loops over all the inner arrays and replaces all "N/A" with a zero and adds them to a new resultant array.

Working Demo

Upvotes: 3

vaso123
vaso123

Reputation: 12391

Try this:

function replaceNa($var) {
    if ($var == 'N/A' ) {
        return 0;
    } else {
        return $var;
    }
}

$array = array(
    array('Pedigre dry', 'N/A', 'N/A', 'N/A'),
    array('Professional Range', 'N/A', 'N/A', 'N/A'),
    array('Pedigree Wet', 'N/A', 'N/A', 'N/A'),
    array('PMM', 'N/A', 'N/A', 'N/A'),
);


foreach ($array as $key => $item) {

    $array[$key] = array_map('replaceNa', $item);
}

var_dump ($array);

Upvotes: 1

acupofjose
acupofjose

Reputation: 2159

I'm sure there's a better answer than this.. but you could always just do the nested foreach approach.

//loop through each Array (first level)
foreach ($arrays as $array) 
{
     //create two variables for each sub array so you have access to keys and values
     foreach ($array as $key=>$value) 
     {
         if ($value = "N/A")
         {
              $value = 0;
         }
     }
}

Upvotes: -1

Related Questions