You can do
$array1 = array('first', 'second', 'third', 'fourth');
$array2 = array('second' => 'bye', 'first' => 'hello', 'third' => 'see you', 'fifth' => 'good evening');
print_r(array_intersect_key( $array2 ,array_flip($array1)));
Output
Array
(
[second] => bye
[first] => hello
[third] => see you
)
Sandbox
array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.
https://www.php.net/manual/en/function.array-intersect-key.php
And
array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.
https://www.php.net/manual/en/function.array-flip.php
Update
I know but it's array1 that is the "string". Array2 is the replacements. See the question: I want to echo hello bye see you fourth
$array1 = array('first', 'second', 'third', 'fourth');
$array2 = array('second' => 'bye', 'first' => 'hello', 'third' => 'see you', 'fifth' => 'good evening');
echo implode(' ', array_intersect_key( array_merge(array_combine($array1,$array1), $array2) ,array_flip($array1)));
Output
hello bye see you fourth
Sandbox
The difference with this one is this bit
$array2 = array_merge(array_combine($array1,$array1), $array2)
What this does is make a new array with array_combine which has the same keys as values. In this case:
array('first'=>'first', 'second'=>'second', 'third'=>'third', 'fourth'=>'fourth')
Then we use the fact that when merging 2 rows the second array will overwrite keys from the first so we merge that with our original $array2
$array2 = array('second' => 'bye', 'first' => 'hello', 'third' => 'see you', 'fourth'=>'fourth', 'fifth' => 'good evening');
So by doing this "extra" step we insure that all elements in $array1 exist in $array2 - the order of $array1 is also preserved - in this case it just adds 'fourth'=>'fourth' but that is exactly what we need for the intersect to work.
Then we just implode it.
UPDATE2
This is a simpler one using preg_filter and preg_replace
$array1 = array('first', 'second', 'third', 'fourth');
$array2 = array('second' => 'bye', 'first' => 'hello', 'third' => 'see you', 'fifth' => 'good evening');
echo implode(' ',preg_replace(preg_filter('/(.+)/', '/(\1)/i', array_keys($array2)), $array2, $array1));
Output
hello bye see you fourth
It's very similar to the str_replace one, so I didn't want to post it as it's own answer. But it does have a few benefits over str_replace. For example
echo implode(' ',preg_replace(preg_filter('/(.+)/', '/\b(\1)\b/i', array_keys($array2)), $array2, $array1));
Now we have \b word boundaries, which means first wont match firstone etc.
Sorry I really enjoy doing things like this, it's "fun" for me.
if (isset($array2[ $extra ])) { .. /* exist */ ..}