I have 2 arrays:
$array_a = array(
array(
"id" => 1,
"merchant_reference" => "Ref 12345"
),
array(
"id" => 2,
"merchant_reference" => "Ref 67890"
),
array(
"id" => 3,
"merchant_reference" => "Ref 11122"
)
);
$array_b = array(
array(
"id" => 1,
"merchant_reference" => "12345"
),
array(
"id" => 2,
"merchant_reference" => "67890"
),
array(
"id" => 3,
"merchant_reference" => "11122"
)
);
And, I'm trying to find 12345
in '$array_b' since Ref 12345
in '$array_a' contains '12345'.
I tried:
$matches = array_filter($array_b, fn($item) => false !== strpos($item['merchant_reference'], $array_a[0]["merchant_reference"]));
if (!!$matches!== false) {
echo "Exists";
} else {
echo "Does not exist";
}
But, this does not work since I'm searching for more characters than are in '$array_b'
CodePudding user response:
You are searching the complete text including the "Ref ". Use a regex for extracting the number.
$matches = [];
preg_match('/Ref (\d )/', $array_a[0]['merchant_reference'], $matches);
$searchRefNumber = $matches[1];
$matches = array_filter($array_b, fn($item) => $searchRefNumber === $item['merchant_reference']);
echo $matches ? 'Exists' : 'Does not exist';
prints
Exists