1

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.

2
  • 1
    if($arr[$key1] == $arr2[$key2]) Does you means something like this? Commented Jan 3, 2015 at 9:16
  • try using this:if($key1 != $key2 && $arr[$key1] == $arr2[$key2]).when keys are different and value is same. Commented Jan 3, 2015 at 9:19

2 Answers 2

1

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>";
        }
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

I think you have identified the heart of my confusion...and that it is a nested foreach which will enable me to integrate through array2 to compare with integration of array1. I'll just check it works or whether there are other problems!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.