Reputation: 417
Within a foreach
iteration in PHP, I wish to check if the value of a key in one array is equal to the value of a different key in another array.
$array1 = array(word1=>"hello",word2=>"world");
$array2 = array(word1=>"hello",word2=>"peter");
I.e. Foreach $array1 as $element if $element [word1=>value] == $array2[word2=>value]
in_array
doesn't seem to be specific enough, since it only looks for the value anywhere in the array. I want just to check for its existence as part of a specific key value pair.
Upvotes: 1
Views: 2024
Reputation: 11859
try like this:if you only worried about value then remove the key inequality checking from if condition.
<?php
$arr=array(1,3);
$arr2=array(3,4,1);
foreach($arr as $key1=>$val1){
foreach($arr2 as $key2=>$val2){
if($key1 != $key2 && $val1 == $val2){// if you do not want to check key inequality remove the first condition.
echo "key1:".$key1.", key2:".$key2." ,value:".$val2."<br>";
}
}
}
Upvotes: 1
Reputation: 4275
Use the code below
<?php
$array1 = array("hello","world");
$array2 = array("hello","peter");
foreach( $array1 as $index => $p){
if($p==$array2[$index]){
echo "they have the same value<br>";
}
else
{
echo "They have different value";
}
}
Hope this helps you
Upvotes: 0