0

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

2
  • 2
    Why not simply use $result = array_intersect_key($Array2, array_flip($Array1)); then loop through $result Commented Apr 27, 2013 at 16:32
  • Thanks Mark, using array_flip() did switch Values/keys as I wanted, can you provide an example for looping through $result. Commented Apr 27, 2013 at 17:22

2 Answers 2

0

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);
0

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..

1
  • there is no need to user regular expression for simply comparing 2 string - there is an overhead while using it Commented Apr 27, 2013 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.