php find word match in array

Hello,

I have a small test script here and I'm trying to match a keyword within an array:  

<?php

$a=array("a splended Volvo runs fast", "XC90", "BMWi", "x5");

foreach($a as $ref) {
 if (true === fnmatch($ref, "Volvo"))
  {
   
   echo " key exists!!!";
 
  }
 else
  {
 
   echo " key does not exist..";
 
   }
 }
 
 ?>

Any suggestions??…script changes or a better way??  It currently does not work, results are:
key does not exist.. key does not exist.. key does not exist.. key does not exist..

And should be:
key exists!!! key does not exist.. key does not exist.. key does not exist..

Thank you
johnsonallstarsAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
It does not work the way you want because you are doing an exact match search, and what you are really after is a substring search. The exact phrase "Volvo" does not exist anywhere in your array. The occurrence of the term "Volvo" only occurs in the first item, as the part of a larger string. Therefore, you cannot do a string equality comparison. Furthermore, why are you using the filename comparison function fnmatch? I don't see any filenames anywhere. Try using strpos instead:

foreach($a as $ref) {
    if (strpos("Volvo", $ref))
    {

Open in new window

0
käµfm³d 👽Commented:
Side comment:  You should really be consistent with where you put your braces. You've got some opening braces on the same line as the item to which they belong (e.g. foreach), and you've got some that are starting on the next line (e.g. if ). Maintaining consistency makes your code easier to read for other developers coming behind you.
0
F PCommented:
Have you tried in_array?

http://php.net/manual/en/function.in-array.php

<?php

$os = array("Mac", "NT", "Irix", "Linux");

if(in_array("NT", $os))
{
    echo "Got NT";
}

if(in_array("mac", $os))
{
    echo "Got mac";
}
0
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

F PCommented:
Also:

http://php.net/manual/en/function.array-search.php - Searches the array for a given value and returns the corresponding key if successful

http://php.net/manual/en/function.array-key-exists.php - Checks if the given key or index exists in the array
0
F PCommented:
Or even better yet:

http://php.net/manual/en/function.preg-grep.php

<?php

$matches = array();
$a = array("a splended Volvo runs fast", "XC90", "BMWi", "x5");

$matches = preg_grep("/^(.*)Volvo(.*)$/", $array);

if(!empty($matches))
{
    echo "found it";
}
0
Ray PaseurCommented:
Can you please post the test data set?  If we have that, we can almost certainly show you a good code solution.  My two favorite references for this kind of question go to the concept of (informal) Test-Driven Development and the SSCCE.
0
Vimal DMSenior Software EngineerCommented:
Hi,

$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
0
johnsonallstarsAuthor Commented:
Ray,

I'm doing this for learning purposes at the moment.  So, not much dataset to go by.   I do like your input though, I've read the articles and much appreciated.

Frank,
I've made some changes and expanded a little bit.  However, I don't think this would work in the long-run, as data would grow and probably take forever to run the script.

<?php

$matches=array();
$a=array("a splended Volvo runs fast", "XC90", "BMWi", "x5");
$s=array("Volvo", "pento", "Mustang");

foreach($s as $ref) {
$matches = preg_grep("/^(.*)$ref(.*)$/", $a);
 
       if(!empty($matches))
       {
            echo "found $ref...";
       } else {
            echo "did not find $ref...";
       }
 }
 ?>

Results: found Volvo… did not find pento… did not find Mustang...

Thank you
0
käµfm³d 👽Commented:
Personally, I don't know why you're jumping ahead to regular expressions. Sure, they work, but if you don't understand why, then you're doing yourself a disservice. You've basically jumped from using a hand saw to using a table saw without understanding how the hand saw works. In the end, if it gets the job done, then it is what it is, but if you're truly in this for the learning, then you should be starting with the basics.
0
johnsonallstarsAuthor Commented:
Ok. I'm searching for words or a string within the array.  The in array search seamed to only work for the exact phrase or key.  If I'm doing it wrong, I can try again on that.
0
Ray PaseurCommented:
Please see: http://iconoun.com/demo/temp_johnsonallstars.php
<?php // demo/temp_johnsonallstars.php

/**
 * http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28660982.html#a40743143
 */
error_reporting(E_ALL);

// TEST DATA FROM THE POST AT EE
$m = [];
$a = [ "a splended Volvo runs fast", "XC90", "BMWi", "x5" ];
$s = [ "Volvo", "pento", "Mustang" ];

// LOOK FOR SUBSTRINGS
foreach ($a as $a_string)
{
    foreach ($s as $s_string)
    {
        if (strpos($a_string, $s_string) === FALSE) continue;
        $m[] = $a_string;
    }
}

// SHOW THE WORK PRODUCT
var_dump($m);

Open in new window

Some good learning resources are identified here:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

Why professionals choose the principles of least astonishment and the most obvious code examples can be summed up in this cartoon.
https://xkcd.com/1171/

Why test data matters more than any code sample:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_7830-A-Quick-Tour-of-Test-Driven-Development.html
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
F PCommented:
This code you posted doesn't make much sense, and you don't escape the $ref, so you have one array, that you want to check each element in it, to see if it exists in another array? Check all element 0 against an array, then all element 1 against the same array? If you have that kind of recursion, I would probably suggest an implode of one array, and a foreach loop with the other. That's probably your best bet.... So:

<?php

$a = array("a splendid Volvo runs fast", "XC90", "BMWi", "x5");
$s = array("Volvo", "pento", "Mustang");

foreach($s as $ref) 
{
    $match_a = implode(' ', $a);

    if(strpos($match_a, $ref) !== FALSE)
    {
        echo "found {$ref}...\n";
    }
    else
    {
        echo "did not find {$ref}...\n";
    }
}

unset($ref, $match_a);

Open in new window


That would give you the same output as what it seemed you were doing in your function above... only cleaner.
0
F PCommented:
Lastly... I hope this helps!!


http://www.phpliveregex.com/
0
johnsonallstarsAuthor Commented:
Thank you all.  Ray I've read several other posts from you and thorough as always.  Many, many thanks!
0
Ray PaseurCommented:
Thanks for the points and best of luck with your project, ~Ray
0
johnsonallstarsAuthor Commented:
Frank,

Your post was also very helpful.  I see how the implode opens up the array now.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.