Jhonny Jr. Jhonny Jr. - 5 months ago 15
PHP Question

Check and count same word on each array

I've been successfully check same word on 2 different array, but my main problem if there is array contain same word of "picture" like on array number 3 -> 3, it just give me result 1.
I want it display exact result like 2 because array number 3 -> 3 contain two "picture" word

Array 1

Array
(
[0] => royalty
[1] => free
[2] => picture
)


Array 2

Array
(
[0] => Array
(
[0] => Affordable and search from millions of royalty free picture
)

[1] => Array
(
[0] => from millions of royalty picture
)

[2] => Array
(
[0] => Provides free picture upload and hosting
)

[3] => Array
(
[0] => Post your picture here Get permanent links picture
)

[4] => Array
(
[0] => Choose your own unique username to access image
)

)


Result

Array 1
(
[0] => 1
[1] => 1
[2] => 0
[3] => 0
[4] => 0
)
Array 2
(
[0] => 1
[1] => 0
[2] => 1
[3] => 0
[4] => 0
)
Array 3
(
[0] => 0
[1] => 1
[2] => 1
[3] => 1
[4] => 0
)


Here is my code

$array1 = array('royalty', 'free', 'picture');

for ($i=0; $i < count($array1); $i++) {
$array2 = array(
array('Affordable and search from millions of royalty free'),
array('from millions of royalty picture'),
array('Provides free picture upload and hosting'),
array('Post your picture here Get permanent links picture'),
array('Choose your own unique username to access image')
);

foreach($array2 as &$item) {
$item = count(array_intersect(explode(' ', $array1[$i]), explode(' ', $item[0])));
}

print_r($array2); }

Answer

Change the array order cause intersect return all array from the first array. Check the below code i have modified. It may helps. Thanks

   $array1 = array('royalty', 'free', 'picture');

   for ($i=0; $i < count($array1); $i++) { 
   $array2 = array(
   array('Affordable and search from millions of royalty free'),
   array('from millions of royalty picture'),
   array('Provides free picture upload and hosting'),
   array('Post your picture here Get permanent links picture picture'),
   array('Choose your own unique username to access image')
  );

  foreach($array2 as &$item) {
      $item = count(array_intersect(explode(' ', $item[0]), explode(' ',     $array1[$i])));
  }

print_r($array2);

I have modified here

**$item = count(array_intersect(explode(' ', $item[0]), explode(' ',     $array1[$i])));**

Thanks,

Comments