saravanan mp
saravanan mp

Reputation: 783

Get matching values and key from array in php

How to get only matching values from an array in php. Example:

<?php
$a=array("1"=>"Hello","2"=>"World","3"=>"Check","4"=>"Here");
?>

from $a, if i have text like "He" or "ld" or "che" , How to show based on text get matching values and keys an array. Same like sql like query.

Upvotes: 0

Views: 1746

Answers (3)

Parixit
Parixit

Reputation: 3855

It's simple one liner.

You might be looking for preg_grep(). Using this function you can find possible REGEX from your given array.

$a=array("1"=>"Hello","2"=>"World","3"=>"Check","4"=>"Here");    
$matches  = preg_grep ("/^(.*)He(.*)$/", $a);
print_r($matches);

Upvotes: 1

trincot
trincot

Reputation: 349964

You could create function for that, like this:

function find_in_list($a, $find) {
    $result = array();
    foreach ($a as $el) {
        if (strpos($el, $find) !== false) {
            $result[] = $el;
        };
    }
    return $result;
}

Here is how you could call it:

print_r (find_in_list(array("Hello","World","Check","Here"), "el"));

output:

Array ( [0] => Hello ) 

Upvotes: 1

eol
eol

Reputation: 24555

You can iterate the array and check every value if it contains your search string:

        $searchStr = 'He';
        $a=array("1"=>"Hello","2"=>"World","3"=>"Check","4"=>"Here");

        foreach( $a as $currKey => $currValue ){
          if (strpos($currValue, $searchStr) !== false) {
             echo $currKey.' => '. $currValue.' ';
          }
        }
//prints 1 => Hello 4 => Here 

Upvotes: 1

Related Questions