开发者

how to search an array in php?

开发者 https://www.devze.com 2023-02-01 18:08 出处:网络
suppose I have an arr开发者_开发问答ay of names, what I want is that I want to search this particular array against the string or regular expression and then store the found matches in another array.

suppose I have an arr开发者_开发问答ay of names, what I want is that I want to search this particular array against the string or regular expression and then store the found matches in another array. Is this possible ? if yes then please can your give me hint ? I am new to programming.


To offer yet another solution, I would recommend using PHP's internal array_filter to perform the search.

function applyFilter($element){
  // test the element and see if it's a match to
  // what you're looking for
}

$matches = array_filter($myArray,'applyFilter');

As of PHP 5.3, you can use an anonymous function (same code as above, just declared differently):

$matches = array_filter($myArray, function($element) {
  // test the element and see if it's a match to
  // what you're looking for
});


what you would need to di is map the array with a callback like so:

array_filter($myarray,"CheckMatches");

function CheckMatches($key,$val)
{
    if(preg_match("...",$val,$match))
    {
        return $match[2];
    }
}

This will run the callback for every element in the array!

Updated to array_filter


well in this case you would probably do something along the lines of a foreach loop to iterate through the array to find what you are looking for.

foreach ($array as $value) {
  if ($searching_for === $value) {/* You've found what you were looking for, good job! */}
}

If you wish to use a PHP built in method, you can use in_array

$array = array("1", "2", "3");
if (in_array("2", $array)) echo 'Found ya!';


1) Store the strings in array1 2) array2 against you want to match 3) array3 in which you store the matches

$array1 = array("1","6","3");
$array2 = array("1","2","3","4","5","6","7");
foreach($array1 as $key=>$value){
  if(in_array($value,$array2))
      $array3[] = $value;
}
echo '<pre>';
print_r($array3);
echo '</pre>';
0

精彩评论

暂无评论...
验证码 换一张
取 消