michaelmcgurk
michaelmcgurk

Reputation: 6523

Find strings inside array using PHP

I have 2 arrays and am looking to find a value inside 1 of the arrays using PHP.

I realise I'd have to use the PHP explode function but I'm afraid that's where my skills end.

My function would compare the values of both arrays and if it finds any $needle values inside $haystack, it would return them inside $found. It could potentially find more than one, so perhaps $found should be an array too?

$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";
$found = magicFunction($needle,$haystick); 
// $found['0'] = "Landscaping";
// $found['1'] = "3D Modelling";

Does this make sense?

Many thanks for any pointers with this.

Upvotes: 0

Views: 2167

Answers (5)

tom
tom

Reputation: 19173

The function you are looking for is built in to PHP: array_intersect.

$a = explode(',', "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling");
$b = explode(',', "Football,Rugby,Landscaping,3D Modelling");
$found = array_intersect($a, $b); 
print_r($found);

Output: Array ( [1] => Landscaping [4] => 3D Modelling )

Upvotes: 1

David Müller
David Müller

Reputation: 5351

PHP provides the handy function array_intersect to do that.

$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";

$needle = explode(",", $needle);
$haystack = explode(",", $haystack);

$intersection = array_intersect($haystack, $needle);
print_r($intersection);
//Array ( [2] => Landscaping [3] => 3D Modelling )

Upvotes: 7

Muatik
Muatik

Reputation: 4171

You can produce arrays from the needle and the haystack, then find intersect of the two arrays:

<?php

$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";

$needle = explode(',', $needle);
$haystack = explode(',', $haystack);


$found = array_intersect($needle, $haystack);

print_r($found);
?>

https://www.php.net/array_intersect

Upvotes: 1

Daniel
Daniel

Reputation: 3806

The easiest way is probably to explode the needles and look for occurrences using strpos.

$needles = explode(',', $needle);
foreach ($needles as $n)
{
      if (strpos($n, $haystack)) {  }
}

Jan Hančič solution may be more appropriate and faster if you do not need the position of the string.

Upvotes: 0

Jan Hančič
Jan Hančič

Reputation: 53929

You could do something like this:

$found = Array ();
$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";
$search = explode(',',$haystack);
foreach ( explode(',',$needle as $k => $v )
{
  if ( in_array ( $v, $search ) )
    $found[] = $v;
}

Or as David has said, you could use array_intersect:

$found = array_intersect ( explode( ',', $haystack ), explode( ',', $needle ) );

Upvotes: 3

Related Questions