2

There are multiple ways to do this I'm sure. I have an array that looks like this:

$map=array(
'ABC'=>'first_three',
'DEF'=>'second_three',
'GHI'=>'third_three'
)

$info=array(
    array('x','XXABCXXXX','x','x','x'),
    array('x','XXXDEFXXXX','x','x','x'),
    array('x','XXXXXXXXXX','x','x','x'),
    array('x','XXXXXXXABC','x','x','x'),
    array('x','XXXXXXXXXX','x','x','x')
)

I want to do a find/replace so that the 2nd string in the array will be compared to the keys in $map and if any are found, they'll replace the key with whatever was in the $map.

array('x','XXfirst_threeXXXX','x','x','x')

I want to loop through $info so:

foreach ($info as $i){
    [something with $i[1] and $map]
}

What's the most efficient way to do this? Does it use "in_array"?

1
  • str_replace() inside the foreach Commented May 5, 2015 at 22:51

2 Answers 2

1

Need $i referenced with & to use this way:

foreach ($info as &$i){
    $i[1] = str_replace(array_keys($map), $map, $i[1]);
}
Sign up to request clarification or add additional context in comments.

Comments

0
foreach($info as $key => $i) {
  foreach($map as $k => $v) {
    // replace the key $k ("ABC") with the value $v ("first_three") in the 2nd element of $info, for each $key
    $info[$key][1] = str_replace($k, $v, $info[$key][1]);
  }
}

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.