0

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.

1
  • Its been really better to understand if you have posted code along with expected output Commented Jun 9, 2015 at 11:29

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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);

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.