Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - replace array value

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.

like image 524
wyman Avatar asked Mar 03 '11 10:03

wyman


1 Answers

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)
like image 172
Deckard Avatar answered Oct 16 '22 12:10

Deckard