Compare a string and a php array and only show the matches

Viewed 91

I have a string that looks like this:

"illustration,drawing,printing"

I have an array that looks like this:

Array (
    [0] => illustration
    [1] => drawing
    [2] => painting
    [3] => ceramics
)

How can I compare the two and only display the terms that exist in both the string and array?

So in the above example, I would want to output something that looks like this:

SKILLS: illustration, drawing

Thank you!

4 Answers

use explode(), array_intersect() and implode()

<?php

$string = "illustration,drawing,printing";

$array = Array (
    0 => 'illustration',
    1 => 'drawing',
    2 => 'painting',
    3 => 'ceramics'
);

$stringArray = explode(',',$string);

$common = array_intersect($stringArray,$array);

echo "Skills :".implode(',',$common);

https://3v4l.org/StqYN

You can do something like this:

Function:

    function functionName($string, $array){
        $skills = '';
        // Create a temp array from your string breaking appart from the commas
        $temparr = explode(",", $string);
        // Iterate through each of the words now
        foreach($temparr as $str){
            // Check to see if our current string is in the array provided
            if(in_array($str, $array)){
                // If it is, then add it to the string "skills"
                $skills .= "${str}, ";
            }
        }
        // Cut the last space and comma off the end of the str.
        $skills = substr($skills, 0, strlen($skills) - 2);
        // Return our results
        return 'SKILLS: '.$skills;
    }

Usage:

    $string = "illustration,drawing,printing";
 
    $array = Array (
        0 => "illustration",
        1 => "drawing",
        2 => "painting",
        3 => "ceramics"
    );
    // Just input our string and the array we want to search through
    echo(functionName($string, $array));

Live Demos:

https://ideone.com/qyqgzo http://sandbox.onlinephpfunctions.com/code/65dc988370ad8ce61ab5ccbc232af4bcf8bd3d42

You could replace the comma , and join the string words on OR | and grep for them. This will match the word anywhere in each array element:

$result = preg_grep("/".str_replace(",", "|", $string)."/", $array);

If you want exact matches only then: "/^(".str_replace(",", "|", $string).")$/"

Firstly convert that string into array.

use array_intersect();

$str = "illustration,drawing,printing";
 
 $ar1 = explode(",",$str);

print_r ($ar1);

$ar2 = Array ("illustration","drawing","painting","ceramics"); 

echo "<br>";
 print_r ($ar2);


$result = array_intersect($ar1, $ar2);


echo "Skills :".implode(',',$result);

OUTPUT:

Array ( 
  [0] => illustration 
  [1] => drawing 
  [2] => printing 
)

Array ( 
  [0] => illustration 
  [1] => drawing 
  [2] => painting 
  [3] => ceramics 
)

SKILLS: illustration, drawing
Related