1

I have tried to filter the string from the array which consists of the word DEVICE.

I have used the following technique to check whether there is a word called having DEVICE in the array but it prints

Match Not found

even though there are strings having word DEVICE.

Here is the attempt that I have tried:

$output= array('football GAME', 'cricket GAME', 'computer DEVICE','mobile DEVICE');
$string = 'DEVICE';
foreach ($output as $out) {
    if (strpos($string, $out) !== FALSE) {
        echo "Match found";
        return true;
    }
}
echo "Match Not found!";
return false;

Required Output:

The output should be:

Match Found.

And also I want to display the list of the items that consist of the word DEVICE like:

computer DEVICE  
mobile DEVICE

What correction do I need here?

1
  • 2
    You have your strpos arguments back-to-front. It's strpos(string $haystack, string $needle) Commented Jul 30, 2018 at 5:01

5 Answers 5

2

A non looping way to solve it is to use preg_grep which is regex on arrays.
The pattern searches for "device" in a case insensitive way and returns any strings that have device in it.

$output= array('football GAME', 'cricket GAME', 'computer DEVICE','mobile DEVICE');
$string = 'DEVICE';
$devices = preg_grep("/" . $string . "/i", $output);
Var_dump($devices);

Output

array(2) {
  [2]=>
  string(15) "computer DEVICE"
  [3]=>
  string(13) "mobile DEVICE"
}

https://3v4l.org/HkQcu

Sign up to request clarification or add additional context in comments.

4 Comments

FYI, preg_grep still loops :). You might also want to run $string through preg_quote()
@Phil Depends on how you see it. Why loop when you don't have too? The Case insensitive was just a "guess" as generally case sensitive searching an array does not give the result you want.
I meant that internally, it still loops over the array ~ github.com/php/php-src/blob/master/ext/pcre/php_pcre.c#L2845. Nice answer anyway, it's very clean
Sure preg_quote can be usefull. OP has to decide if that is needed. I would say that all array_functions loop. The thing that makes the difference is if it's done faster internal or in PHP and what you find easiest to read.
2

You've interchanged the arguments in the strpos(). The word to be searched is second argument in the function and the string is first.

int strpos (string $haystack , mixed $needle [, int $offset = 0 ])

Use the code below to get required output:

    $output= array('football GAME', 'cricket GAME', 'computer DEVICE','mobile DEVICE');
    $string = 'DEVICE';
    foreach ($output as $out) {
        if (strpos($out, $string) !== FALSE) {
              // You can also print the matched word using the echo statement below.
              echo "Match found in word: {$out} <br/>";
              return true;
        }
    }
    echo "Match Not found!";
    return false;

Comments

1

You have the position of the strpos fuction's arguments reversed. From php.net:

int strpos (string $haystack , mixed $needle [, int $offset = 0 ])

Therefore you should replace LINE 5 with the following

 if (strpos($out, $string) !== FALSE) {

[1] https://secure.php.net/manual/en/function.strpos.php

Comments

1

Your issue is that your strpos() arguments are backwards. The API is

int strpos( string $haystack, mixed $needle [, int $offset = 0 ] )


As to your other question...

...also I want to display the list of the items that I consists of the word DEVICE

you could create an array of the matching elements via array_filter()

$string = 'DEVICE';
$filtered = array_filter($output, function($out) use ($string) {
    return strpos($out, $string) !== false;
});

echo implode(PHP_EOL, $filtered);
if (count($filtered) > 0) {
    echo 'Match found';
    return true;
}
echo 'Match Not found!';
return false;

Comments

0

If you want to access the filtered array (of strings containing DEVICE), then you can no longer enjoy the performance benefits of an early return. You must iterate the entire input array -- with a classic loop or an array iterating function. I must state that your requirements do not call for the might of a regular expression; making iterated regex evaluations should be reserved for cases where simpler, native string functions are less suitable.

Boiled down, you need to make iterated case-sensitive checks and include strings which contain your qualifying keyword.

From PHP7.4, arrow functions allow more concise anonymous functions syntax and allow the omission of a use() call.

From PHP8, str_contains() is available and is perfectly suited to your required matching.

To find out if any strings qualified, just check the boolean evaluation of your output array.

Code: (Demo)

$input= [
    'football GAME',
    'cricket GAME',
    'computer DEVICE',
    'mobile DEVICE'
];
$needle = 'DEVICE';

$output = array_filter($input, fn($haystack) => str_contains($haystack, $needle));

var_export(
    [
        'filtered' => $output,
        'found' => $output ? 'yes' : 'no'
    ]
);

Output:

array (
  'filtered' => 
  array (
    2 => 'computer DEVICE',
    3 => 'mobile DEVICE',
  ),
  'found' => 'yes',
)

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.