Replace multiple values in a variable

204 views Asked by At

I'm looking forward a solution to replace multiple values from one of my variable ($type)

This variable can have 34 values (strings). I would like to find a way to create a new variable ($newtype) containing new strings from the replacement of my $type.

I think using str replace would be a good solution, but the only way I see things is creating a big "If ..." (34 times?) but does not seem the best way..

Thanks in advance for you help.

Best regards.

2

There are 2 answers

0
hawkyhawk14 On

I would advise against storing a string on multiple values in a variable as it will just get messy!

Store variables in an array in the following way

$type['value1'] = 'cheese';
$type['value2'] = 'ham';

Then if you need to change it you can just do

$type['value2'] = 'chicken';

and you will get (if using print_r)

Array
(
    [value1] => cheese
    [value2] => chicken
}

This means all your values will be neatly stored next to a relevant key and be easily accessable as part of an individual request

echo $type['value1']

which will echo out

Cheese
0
Naryl On

You can use preg_replace with arrays:

$from[0]='from1';
$from[1]='from2';
$from[2]='from3';
$to[0]='to1';
$to[1]='to2'; 
$to[2]='to3';

$newtype=preg_replace($from, $to, $type);

I have never used it like this but the documentation says that you need to use ksort to correctly match the order of the replaces:

$from[0]='from1';
$from[1]='from2';
$from[2]='from3';
$to[0]='to1';
$to[1]='to2'; 
$to[2]='to3';

ksort($to);
ksort($from);

$newtype=preg_replace($from, $to, $type);