0

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.

1
  • Could you please elaborate what you are trying to do? I am not complete sure on what you wan't to do. Are you trying to se if "He" exist in the array? Commented Jan 22, 2016 at 11:12

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

1

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 ) 

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.