Reputation: 119
I have two arrays with same number of members (always)$userInputArr=array("z","z","E","z","z","E","E","E","E","E");
and $user2InputArr=array("a","a","a","z","a","E","E","E","a","E");
I know how to find matching members in two arrays. Here I want to find matching elements with similar indexes e.g. if $userInputArr[4] == $user2InputArr[4], increment $matches. In my attempt below, I loop through both arrays but I cannot get $matchs to increment.
$match = 0;
for ($c =0; $c < count($$userInputArr); $c++) {
for ($d = $c; $d<count($user2InputArr);$d++) {
if ($userAnsStrArr[$c] == $userInputArr[$d]) {
$match = $match +1;
}
}
}
Upvotes: 0
Views: 1551
Reputation: 110
I seems your code not need two for loop increase match in single loop see below code.
<?php
$userInputArr=array("z","z","E","z","z","E","E","E","E","E");
$user2InputArr=array("a","a","a","z","a","E","E","E","a","E");
$match = 0;
for ($c =0; $c < count($userInputArr); $c++) {
if ($user2InputArr[$c] == $userInputArr[$c]) {
$match = $match + 1;
}
}
echo $match;
?>
Upvotes: 0
Reputation: 8249
Here is the code for you. Just use one foreach
, traverse through first array
, and check for the key-value
in second array
.
$s = array("z","z","E","z","z","E","E","E","E","E");
$b = array("a","a","a","z","a","E","E","E","a","E");
foreach($s as $k => $v) {
if($b[$k] === $s[$k]) {
echo $k . ' is the index where keys and values exactly match with value as ' . $b[$k];
}
}
And Output:
3 is the index where keys and values exactly match with value as z
5 is the index where keys and values exactly match with value as E
6 is the index where keys and values exactly match with value as E
7 is the index where keys and values exactly match with value as E
9 is the index where keys and values exactly match with value as E
And here is the link: https://3v4l.org/eX0r4
Upvotes: 0
Reputation: 72226
This question is the perfect example for the PHP function array_intersect_assoc()
:
$array1 = array("z","z","E","z","z","E","E","E","E","E");
$array2 = array("a","a","a","z","a","E","E","E","a","E");
// Find the matching pairs (key, value) in the two arrays
$common = array_intersect_assoc($array1, $array2);
// Print them for verification
print_r($common);
// Count them
$match = count($common);
echo($match." common items.\n");
The output is:
Array
(
[3] => z
[5] => E
[6] => E
[7] => E
[9] => E
)
5 common items.
Upvotes: 1
Reputation: 11
This works for me
$i = sizeof($userInputArr);
$match = 0;
for($j = 0; $j < $i; $j++)
if ($userInputArr[$j] == $user2InputArr[$j]) {
$match = $match +1;
}
Upvotes: 0
Reputation: 121
$match = 0;
for ($c =0; $c < count($$userInputArr); $c++) {
if ($userAnsStrArr[$c] == $userInputArr[$c]) {
$match = $match +1;
}
}
You should do like this.
Upvotes: 0