Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check array data that matches from random characters in php?

Tags:

arrays

php

search

I have an array like below:

$fruits = array("apple","orange","papaya","grape")

I have a variable like below:

$content = "apple";

I need to filter some condition like: if this variable matches at least one of the array elements, do something. The variable, $content, is a bunch of random characters that is actually one of these available in the array data like below:

$content = "eaplp"; // it's a dynamically random char from the actual word "apple`

what have I done was like the below:

$countcontent = count($content);

for($a=0;$a==count($fruits);$a++){

      $countarr = count($fruits[$a]);

      if($content == $fruits[$a] && $countcontent == $countarr){
          echo "we got".$fruits[$a];
      }

}

I tried to count how many letters these phrases had and do like if...else... when the total word in string matches with the total word on one of array data, but is there something that we could do other than that?

like image 612
Gagantous Avatar asked Apr 28 '18 23:04

Gagantous


Video Answer


1 Answers

We can check if an array contains some value with in_array. So you can check if your $fruits array contains the string "apple" with,

in_array("apple", $fruits)

which returns a boolean.

If the order of the letters is random, we can sort the string alphabetically with this function:

function sorted($s) {
    $a = str_split($s);
    sort($a);
    return implode($a);
}  

Then map this function to your array and check if it contains the sorted string.

$fruits = array("apple","orange","papaya","grape");
$content = "eaplp";
$inarr = in_array(sorted($content), array_map("sorted", $fruits));

var_dump($inarr);
//bool(true)

Another option is array_search. The benefit from using array_search is that it returns the position of the item (if it's found in the array, else false).

$pos = array_search(sorted($content), array_map("sorted", $fruits));

echo ($pos !== false) ? "$fruits[$pos] found." : "not found.";  
//apple found.
like image 173
t.m.adam Avatar answered Nov 15 '22 20:11

t.m.adam