search in array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

search in array

Post by yaron »

Hello all,
I want to perform a search through my array if a specific value is contained in one of the array elements.
php function search_array() is not helpful to me because it returns true only if the the values are the same.
I want to do a LIKE search meaning if there is a substring in the array element that matches my search!

I know I can loop the array myself and use substr.
is there a better way?

Thanks
murph
Forum Commoner
Posts: 29
Joined: Fri Oct 03, 2003 1:28 pm
Location: washington

Post by murph »

in_array ( )
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

in_array() wont probably help if you are to use LIKE (as sql's like clause).

A foreach-loop looping the values combined with a regexp or strstr would do the trick.

Code: Select all

<?php
// small example, using strstr
    $array = array('cows', 'fooobars', 'EVILkittens');
    $searchfor = 'ooo';
    foreach ($array as $v) {
        if (strstr($v, $searchfor)) {
            echo 'Found: '.$v;
        }
    }
?>

Returns:
Found: fooobars
Post Reply