php - replace array value

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)

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.


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
)

Tags:

Php