0

I have 2 arrays:

$array1 = array('first', 'second', 'third', 'fourth');
$array2 = array('second' => 'bye', 'first' => 'hello',  'third' => 'see you', 'fifth' => 'good evening');

and I echo the content of $array1 like

foreach ($array1 as $extra) {
echo $extra; }

What I am trying to do is to check every time before echoing the $extra whether the output is found in $array2. And if yes, to echo the value of the array2 instead.

So in my example above, instead of first second third fourth I want to echo hello bye see you fourth.

How can I do this?

1
  • if (isset($array2[ $extra ])) { .. /* exist */ ..} Commented Mar 27, 2019 at 21:55

5 Answers 5

2

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.

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

8 Comments

There is no fourth
@Andreas - there is no forth in $array2 either. You can't output something that doesn't exist.
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
Ok, I can fix that and keep it one line :)
I'm not so sure you can :-) I thought about a solution like this before. Mind the overhead looping in the background
|
2

You can access $array2[$key] and use the null-coalescing operator since you apparently want to fall back to the value from $array1 if it doesn't exist as a key in $array2.

foreach ($array1 as $key) {
  echo $array2[$key] ?? $key, ' ';
  // [PHP5] echo isset($array2[$key]) ? $array2[$key] : $key, ' ';
}

Demo: https://3v4l.org/3vQYt

Note: this adds a potentially unwanted space at the end. If that's the case, either add a condition to the loop or do something like this instead:

echo implode(' ', array_map(function ($key) use ($array2) { 
  return $array2[$key] ?? $key;
  // [PHP5] return isset($array2[$key]) ? $array2[$key] : $key;
}, $array1));

Demo: https://3v4l.org/VCDVt

7 Comments

Hello, thank you for this, can you please help me on writing it to php 5.6 instead of 7?
Thanks again. One last question, I just noticed that the array I explode is like this array(23) { [0]=> string(3) "ABS" [1]=> string(3) "ESP" [2]=> string(8) "Airbag 6" is this structure something that the code can not handle?
@EnexoOnoma You mean $array1 or $array2? If it's your $array1 then it's perfectly fine, if it's your $array2 then the values from $array1 need to be these numeric indexes themselves. You can use 3v4l.org to show me an example if you'd like.
the above sample array is my array1 and is exploded from a string like ABS,ESP,Airbag 6. the format oft he array2 is like the one I posted in the question. Unfortunately i can't make it work though
hey I made it work! thank you for your help and guidance!
|
1
foreach ($array1 as $extra) {
      foreach ($array2 as $key=>$value) {
          if($extra==$key){
               echo $value;
          }
      }
}

something like this

Comments

1

Just use isset:

foreach($array1 as $e) {
    $val = isset($array2[$e]) ? $array2[$e] : $e;
    echo $val;
}

Doc can be found here: https://www.php.net/manual/en/function.isset.php

Comments

1

You can just implode the first array then use str_replace to replace the words from the second in the imploded string.
No need for loops in my opinion.

echo str_replace(array_keys($array2), $array2, implode(" ", $array1));
//hello bye see you fourth

Array_keys will take the keys from array2 and make them the find, then the values from array2 will be the replacements.

https://3v4l.org/UIWV0

2 Comments

Doesn't work if keys have the same substrings in them. E.g. if you replace first with firstsecond.
@Jeto True. There are limits with str_replace.

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.