12

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.

0

10 Answers 10

15

A bit more elegant and shorter solution.

$aArray = array('work','home','sky','door');   

foreach($aArray as &$sValue)
{
     if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}

The & operator is a pointer to the particular original string in the array. (instead of a copy of that string) You can that way assign a new value to the string in the array. The only thing you may not do is anything that may disturb the order in the array, like unset() or key manipulation.

The resulting array of the example above will be

$aArray = array('work','home', 0, 0)
Sign up to request clarification or add additional context in comments.

Comments

11

A loop will perform a series of actions many times. So, for each element in your array, you would check if it is equal to the one you want to change and if it is, change it. Also be sure to put quote marks around your strings

//Setup the array of string
$asting = array('work','home','sky','door')

/**
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] == 'home')
       $asting[$i] = 0;
}

Here is some suggested reading:

http://www.php.net/manual/en/language.types.array.php

http://www.php.net/manual/en/language.control-structures.php

But if you are struggling on stuff such as looping, you may want to read some introductory programming material. Which should help you really understand what's going on.

2 Comments

You'd want to do $asting[$i] = 0;.
is there any way to do this task without loop? smart way?
1

A bit other and much quicker way, but true, need a loop:

//Setup the array of string
    $asting = array('bar', 'market', 'work', 'home', 'sky', 'door');

//Setup the array of replacings
    $replace = array('home', 'work');

//Loop them through str_replace() replacing with 0 or any other value...
    foreach ($replace as $val) $asting = str_replace($val, 0, $asting);

//See what results brings:    
    print_r ($asting);

Will output:

Array
(
    [0] => bar
    [1] => market
    [2] => 0
    [3] => 0
    [4] => sky
    [5] => door
)

1 Comment

Won't str_replace search inside each string? So it would also replace 'hard work' and 'homestay' with 0.
1

An alternative using array_map:

$original = array('work','home','sky','door');

$mapped = array_map(function($i){
    $exclude = array('work','home');
    return in_array($i, $exclude) ? 0 : $i; 
}, $original);

Comments

1

you may try array_walk function:

function zeros(&$value) 
{ 
    if ($value != 'home' && $value != 'work'){$value = 0;}      
}   

 $asting = array('work','home','sky','door','march');   

 array_walk($asting, 'zeros');
 print_r($asting);

Comments

0

You can also give array as a parameter 1 and 2 on str_replace...

1 Comment

how about my array is infinity to add from the form submitted, but I want to replace the value to 0 exclude the work & home only?
0

Just a small point to the for loop. Many dont realize the second comparing task is done every new iteration. So if it was a case of big array or calculation you could optimize loop a bit by doing:

for ($i = 0, $c = count($asting); $i < $c; $i++) {...}

You may also want to see http://php.net/manual/en/function.array-replace.php for original problem unless the code really is final :)

1 Comment

But array_replace looks for "values having the same keys"
0

Try This

$your_array = array('work','home','sky','door');
$rep = array('home', 'work');
foreach($rep as $key=>$val){
     $key = array_search($val, $your_array);
     $your_array[$key] = 0;
}
print_r($your_array);

1 Comment

Why should researchers "try this"? Why do you declare $key in your foreach() then immediately overwrite it on the next line? What if $val is not found in $your_array? ... array_search() will return false and false will be converted to 0 and replace the first element in $your_array no matter what its value is. I think it would be more accurate to say: "Don't try this".
0

There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise. For best maintainability, I recommend separating your list of targeted string as a lookup array. By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.

Code: (Demo)

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

$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);

foreach ($array as &$v) {
    $v = $lookup[$v] ?? 0;
}

var_export($array);

Output:

array (
  0 => 'work',
  1 => 0,
  2 => 'home',
  3 => 0,
  4 => 0,
)

You can very easily, cleanly extend your list of targeted strings by merely extending $keep.


If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)

var_export(
    array_map(fn($v) => $lookup[$v] ?? 0, $array)
);

Comments

-1

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;

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.