im@markvi.eu

The preg_​grep() func­tion in PHP can be used to search for array val­ues that match a spe­cif­ic pat­tern. The func­tion takes two para­me­ters: the reg­u­lar expres­sion to match and the input array. It returns an array con­tain­ing all ele­ments of the input array that match the reg­u­lar expres­sion provided.

Here is an exam­ple of how you can use preggrep() to find all array val­ues that start with ID”:

$array = array("ID_123", "ID_456", "ID_789", "other_value", "another_value");
$result = preg_grep("/^ID_/", $array);
print_r($result);

The above code will out­put an array con­tain­ing the ele­ments ID_123”, ID_456”, and ID_789”.

The arrayfil­ter() func­tion is anoth­er way to achieve this. It iter­ates over the input array and applies a call­back func­tion on each ele­ment. The call­back func­tion checks if the val­ue starts with ID” by using str­pos() func­tion and returns true if the val­ue starts with ID_’ oth­er­wise false. Then array_​filter() func­tion fil­ters the array and keeps the ele­ment that returns true from the call­back function.

$array = array("ID_123", "ID_456", "ID_789", "other_value", "another_value");
$result = array_filter($array, function($val) { return strpos($val, 'ID_') === 0; });
print_r($result);

It’s impor­tant to note that the preg_​grep() uses reg­u­lar expres­sion which is a pow­er­ful way of match­ing pat­terns in strings but it can be com­pu­ta­tion­al­ly expen­sive and a bit hard­er to under­stand for some peo­ple. While array_​filter() is a sim­pler way of achiev­ing this but it may be less effi­cient if you have a large dataset. It’s up to you to decide which method to use based on your spe­cif­ic use case and the size of your data.

Similar Articles