Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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

share|improve this question
    
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). – JackTheKnife Aug 21 '14 at 18:30

2 Answers 2

up vote 2 down vote accepted

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

share|improve this answer
    
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. – JackTheKnife Aug 21 '14 at 18:11
    
okay. then try my updated answer. – Awlad Liton Aug 21 '14 at 18:15
    
Updated answer works for me – JackTheKnife Aug 21 '14 at 19:11

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;
share|improve this answer
    
Requires little bit of modification to get result as as string not an array, but will work too in my case. Thanks! – JackTheKnife Aug 21 '14 at 19:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.