0

I have a word:

 $word = "samsung";

I have array:

$myarray = Array(
[0] => "Samsung=tv"
[1] => "Apple=mobile"
[2] => "Nokia=mobile"
[3] => "LG=tv"

I need now something like this to find a partial match:

 if($word in $myarray){ echo "YES"; } // samsung found in Samsung=tv

Thank you for help.

5 Answers 5

3

You want in_array https://www.php.net/manual/en/function.in-array.php.

if(in_array($word,$myarray){ echo 'yes'; }
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, in_array() reply true only if I search full string, samsung=tv. I need only samsung search inside string samsung=tv
but I guess that searching for samsung in Samsung=tv is not valid.
1

Are you looking for something like this?

<?php
$myarray = array("Samsung=tv", "Apple=mobile", "Nokia=mobile", "LG=tv");


function findSimilarWordInArray($word, $array) {

    if (empty($array) && !is_array($array) return false;

    foreach ($array as $key=>$value) {
        if (strpos( strtolower($value), strtolower($word)) !== false) {
            return true;
        } // if
    } // foreach

}

// use case

if ( findSimilarWordInArray('samsung',$myarray) ) {
    echo "I've found it!";
}
?>

It allows you to look for a similar word in array values.

Comments

1

If you are looking for partial matches, you can use strpos() with a foreach loop to iterate through the array.

foreach ($myarray as $key => $value) {

    if (strpos($value, $word) !== FALSE) {
        echo "Yes";
    }

}

Comments

1

There is no built in function to do a partial match, but you can easily create your own:

function in_array_partial($needle, $haystack){
    $result = false;

    $needle = strtolower($needle);
    foreach($haystack as $elem){
        if(strpos(strtolower($elem), $needle) !== false){
            $result = true;
            break;
        }
    }
    return $result;
}

Usage:

if(in_array_partial('samsung', $myarray)){
    echo 'yes';
}

Comments

0

You can try something like this:

function my_in_array($word, $array){
 forach($array as $value){
  if(strpos($word, $value) !== false){
   return true;
  }
 }
return false;
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.