JackTheKnife
JackTheKnife

Reputation: 4144

Replace string with values from multidimensional array based on a key

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

Upvotes: 1

Views: 1246

Answers (2)

Awlad Liton
Awlad Liton

Reputation: 9351

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

Upvotes: 2

jh314
jh314

Reputation: 27802

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;

Upvotes: 0

Related Questions