Search for partial value match in an Array in PHP

PHPServer Side ProgrammingProgramming

The array_filter function can be used to match a partial value in an array. A callback can be provided, that helps in deciding which elements would remain in the array and which would be removed.

When the callback returns false, it means the given element needs to be removed. Below is a code example demonstrating the same −

$arr = array(0 => 'abc', 1 => 'def', 2 => 'ghijk', 3 => 'lmnxyz');
$results = array();
foreach ($arr as $value) {
   if (strpos($value, 'xyz') !== false) { $results[] = $value; }
if( empty($results) ) { echo 'No matches found.'; }
else { echo "'xyz' was found in: " . implode('; ', $results); }

Parsing JSON array with PHP foreach −

'xyz' was found in: lmnxyz
Updated on 07-Apr-2020 11:20:43