phparraysreplaceblacklist

Replace non-specified array values with 0


I want to replace all array values with 0 except work and home.

Input:

$array = ['work', 'homework', 'home', 'sky', 'door']

My coding attempt:

$a = str_replace("work", "0", $array);

Expected output:

['work', 0, 'home', 0, 0]

Also my input data is coming from a user submission and the amount of array elements may be very large.


Solution

  • this my final code

    //Setup the array of string
    $asting = array('work','home','sky','door','march');
    
    /**
    Loop over the array of strings with a counter $i,
    Continue doing this until it hits the last element in the array
    which will be at count($asting)
    */
    for($i = 0; $i < count($asting); $i++) {
    //Check if the value at the 'ith' element in the array is the one you want to change
    //if it is, set the ith element to 0
    if ($asting[$i] == 'work') {
       $asting[$i] = 20;
    } elseif($asting[$i] == 'home'){
        $asting[$i] = 30;
    
    }else{
        $asting[$i] = 0;
    }
    
    echo $asting[$i]."<br><br>";
    
    $total += $asting[$i];
    }
    
    echo $total;