1

I have a variable with multiple number stored as a string:

$string = "1, 2, 3, 5";

and multidimensional array with other stored values:

$ar[1] = array('title#1', 'filename#1');
$ar[2] = array('title#2', 'filename#2');
$ar[3] = array('title#3', 'filename#3');
$ar[4] = array('title#4', 'filename#4');
$ar[5] = array('title#5', 'filename#5');

My goal is to replace number from $string with related tiles from $ar array based on associated array key. For an example above I should to get:

$string = "title#1, title#2, title#3, title#5";

I have tried to loop through $ar and do str_replace on $string, but final value of $string is always latest title from related array.

foreach($ar as $key => $arr){
  $newString = str_replace($string,$key,$arr[0]);
}

Any tips how to get this solved?

Thanks

1
  • In which point is off topic? I'm stuck on something which I'm not able to solve (my code is not working as I expect). Commented Aug 21, 2014 at 18:30

2 Answers 2

2

you can do it by str_replace by concat each time or you can do it by explode and concat.

Try Like this:

$string = "1, 2, 3, 5";
$arrFromString = explode(',', $string);
$newString = '';
foreach($ar as $intKey => $arr){
    foreach($arrFromString as $intNumber){
        if($intKey == $intNumber) {
            $newString .= $arr[0].',';
        }
    }
}
$newString = rtrim($newString,',');
echo $newString;

Output:

title#1,title#2,title#3,title#5

live demo

Sign up to request clarification or add additional context in comments.

1 Comment

Well, your example is not a solution in my case because you are using values from array $ar not a keys of that array to get right title, which btw can be "Title of the product" without a number.
0

You can use explode() and implode() functions to get the numbers in $string as an array and to combine the titles into a string respectively:

$res = array();
foreach (explode(", ", $string) as $index) {
     array_push($res, $ar[$index][0]);
}
$string = implode(", ", $res);
print_r($string);

will give you

title#1, title#2, title#3, title#5;

1 Comment

Requires little bit of modification to get result as as string not an array, but will work too in my case. Thanks!

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.