how to search an array in php?

≡放荡痞女 提交于 2020-01-16 21:35:27

问题


suppose I have an array 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.


回答1:


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




回答2:


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
});



回答3:


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!';



回答4:


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>';


来源:https://stackoverflow.com/questions/4530453/how-to-search-an-array-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!