0

Is it possible to check if an array contains at least one value from a string? The string is an outputted list (see below).

This is my array, let's call it $data

Array ( [0] => finance-accounting-banking [1] => fixed-term [2] => human-resources [3] => international [4] => logistics-supply-chain [5] => management [6] => marketing )

And this is my outputted list, let's call it $types.

fixed-term|marketing

I thought this might've worked but no such luck...

if (in_array($types, $data))
2
  • You should be able to split the list into individual terms and use in_array on each. Looks like you may be searching for "fixed-term|marketing" which doesn't actually exist. Commented Jul 14, 2016 at 21:07
  • @ckimbrell Yep, exactly. I'll give that a go. Commented Jul 14, 2016 at 21:09

3 Answers 3

2

If your $types variable will have the values separated by |, here is a code that doesn't use preg:

$data = array ( 0 => 'finance-accounting-banking', 1 => 'fixed-term', 2 => 'human-resources', 3 => 'international', 4 => 'logistics-supply-chain', 5 => 'management', 6 => 'marketing' );
$types = 'fixed-term|marketing';

if(count(array_intersect($data, explode('|', $types))) > 0){
    echo 'found';
}else{
    echo 'not found';
}
Sign up to request clarification or add additional context in comments.

Comments

1

If $types is exactly in the format that you mentioned, you can do it simply by using preg_grep() function:

$atLeastOne = count(preg_grep('/' . $types . '/', $input)) != 0;

Comments

0
$pieces = explode('|',$types);
foreach ($pieces as $element) {
    if ( in_array($element,$data) ) {
        echo "found";
    }
}

2 Comments

type 1 -- Call to undefined function array_in(). in_array()
Hint: break the loop once the value's found to avoid: 1- echoing found multiple times; 2- needles iterations;

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.