Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Intersection of array containing substrings of another one

I have these 2 arrays:

array(
  100 => 'this is some text',
  161 => 'prefix1 : this is some text',
  224 => 'some other text',
  356 => 'prefix2 : some other text',
  // ...
)

and

array(
  0 => 'prefix1',
  1 => 'prefix2',
  // ...
)

The first array should not contain the prefixes, so I would like to identify the errors like this as a result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array(
  161 => 'prefix1 : this is some text',
  356 => 'prefix2 : some other text',
  // ...
)

>Solution :

You can use array_filter with str_contains like:

$a = [
  100 => 'this is some text',
  161 => 'prefix1 : this is some text',
  224 => 'some other text',
  356 => 'prefix2 : some other text',
  ];


$b = ['prefix1','prefix2'];

print_r(array_filter($a, function($a) use ($b){
    foreach($b as $pref){
        if(str_contains($a, $pref)){
            return true;
        }
    }
}));

Output:

Array
(
    [161] => prefix1 : this is some text
    [356] => prefix2 : some other text
)

Example:

https://sandbox.onlinephpfunctions.com/c/c55a9

Reference:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading