Home > database >  Check if an array has certain characters
Check if an array has certain characters

Time:02-02

Is there a way to check if an array has certain characters, not the whole value? I want to return true in the follow expression, by locating "Pe".

$people = array("Peter", "Joe", "Glenn", "Cleveland", 23);

if (in_array("Pe", $people, TRUE))
  {
  echo "Match found";
  }

CodePudding user response:

Iterate over each item and check if the given name contains your string.

foreach ($people as $person) {
   if (str_starts_with('Pe', $person)) {
      echo "Match found";
   }
}

CodePudding user response:

You can use array_filter() and preg_grep() functions in PHP to check if an array has certain characters. Here is an example:

$array = array("Hello", "World", "How", "Are", "You");
$characters = array("o", "W");

$result = array_filter($array, function ($value) use ($characters) {
   return count(array_intersect(str_split(strtolower($value)), $characters)) > 0;
});

print_r($result);

This will return an array of elements that contain at least one of the characters specified in the $characters array:

Array
(
    [0] => Hello
    [1] => World
)

Alternatively, you can use preg_grep() function to achieve the same result.

CodePudding user response:

With PHP 8 you can do this with str_contains:

if (str_contains('How are you', 'a')) { 
    echo 'true';
}

Before PHP 8

You can use the strpos() function which is used to find the occurrence of one string inside another one:

$haystack = 'How are you?';
$needle   = 'ar';

if (strpos($haystack, $needle) !== false) {
    echo 'true';
}
  • Related