Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Using explode('<br>',$String) I have an Array1 with sub-Strings.

I want to use an Array2 as needles to loop through Array1 and if a Sub-String is found return Array2 values.

Example:

$Array1 { [0]=> string(3) "red"
          [1]=> string(4) "Blue"
          [3]=> string(5) "Black" };


$Array2 [
        'red' => "Red",
        'Yellow' => "Yellow"];

What is the best method/function to approach this task.

In the example above the Array1 ( Haystack) has a substring "red" , I want to be able to define Key => values in Array2 to use as needles and when for example a certain Key is found return its value.

// Output above

"Red"

Thanks

share|improve this question
2  
Why not simply use $result = array_intersect_key($Array2, array_flip($Array1)); then loop through $result – Mark Baker Apr 27 at 16:32
42[][][][][[][][][[] – PeeHaa 埽 Apr 27 at 16:59
Thanks Mark, using array_flip() did switch Values/keys as I wanted, can you provide an example for looping through $result. – Raj Apr 27 at 17:22

2 Answers

You can do it with a simple foreach loop

function getColorOrSomething(&$array1, &$array2){
    foreach($array2 as $key=>$value)
         if(in_array($key, $array1))
            return $value;


     return null; //no match found

}

and then of course call the function with the 2 arrays

$selected = getColorOrSomething($array1, $array2);
share|improve this answer

You can use a nested loop like this:

$key = "";
$value = "";

foreach( $Array1 as $ar1 ) {
    foreach( $Array2 as $ak2=>ar2 ) {
        if( preg_match("/" . $ak2 . "/", $ar1) ) {
            $key = $ak2;
            break;
        }

        if( $key != "" ) {
            $value = $ar1; 
            break;
        }
    }
}

echo "Key: " . $key . " & Value: " . $value;

Like so..

share|improve this answer
there is no need to user regular expression for simply comparing 2 string - there is an overhead while using it – Yaron U. Apr 27 at 17:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.