1

Is it possible to do something similar to the following, I've tried but couldn't get any variations of this to work:

$hello_all = array($str . ' World', $str . ' Universe');

function combine(&$arr){
  $str = 'Hello';
  print_r($arr);
}

combine($hello_all);

And I'd like to get something like this:

Array ( [0] => Hello World [1] => Hello Universe )

Is there a better approach?

4
  • yes, but not that way - just the other way round. The concatanation would be IN a function. Commented Jun 22, 2017 at 0:53
  • 1
    What do you really want to achieve? I mean, 'Hello' won't be hard coded, will it? Commented Jun 22, 2017 at 0:55
  • No, not hard coded. It's another variable but I wanted to simplify the example down to the part that I was questioning. Commented Jun 22, 2017 at 1:05
  • You could of course do a kind of templating with preg_replace and things like array('#replace# World'), but that would be much slower than Patrick's solution Commented Jun 22, 2017 at 1:09

2 Answers 2

3

I would probably do it like this

$hello_all = array('World', 'Universe');

function combine($arr, $str){

  foreach($arr as $key=>$value){
    $new[] = $str.$value;
  }

  return $new;
}

$print = combine($hello_all, 'Hello ');
print_r($print);

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

6 Comments

yes, but please put the print_r() outside of the function, and let the function just return the new array. Just for my eyes....
...forgot the return
Yup I agree. I made the changes
Your right since the print_r is no longer in the function
This makes sense. I think I simplified my example a bit too much. But the array would be closer to this: $hello_all = array('Hidey ho ' . $str . ' World', 'We come in peace ' . $str . ' Universe');
|
0

Yup something like this in that case:

$hello_all = array('World *word*', 'Universe *word*', '*word* mom', 'Hey santa! *word* to you!');

function combine($arr, $str, $find){

  foreach($arr as $key=>$value){
    $new[] = str_replace($find, $str, $value);
  }

  return $new;
}

$print = combine($hello_all, 'Hello', '*word*');
print_r($print);

?>

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.