Reputation: 38
Hi I have two arrays and I want to check them if they have any element equal (same) with each other and if they have they should get on the page if not just print No.
I have made this code but i do not know why it doesn't work.
P.S. the elements of arrays contain text.
$res = count($title1);
for ($j = 0; $j <= $res; $j++) {
if(strtoupper($title2[$j]) == strtoupper($title1[$j]))
{
echo 'Yes<br/>';
echo $title2[$j].'==='.$title1[$j].'<br/';
}
else{
echo 'No<br/>';
}
}
Upvotes: 0
Views: 1879
Reputation: 56
foreach ($array1 as $value) {
if(in_array($value , $array2)
{
echo 'Yes<br/>';
echo $value;
$count = $count + 1 ;
}
}
this is the right answer :) thnx @hamidreza
Upvotes: 0
Reputation: 65
You can use this too
<?php
$count = 0
foreach ($array1 as $value) {
if(in_array($value , $array2)
{
echo 'Yes<br/>';
echo $value;
$count = $count + 1 ;
}
}
if($count == 0 )
{
echo "no" ;
}
?>
Upvotes: 1
Reputation: 64657
I can only guess, as we don't know what the arrays contain, but I assume you want to check if they have the same element at any index. At the moment, you are only checking if $title1
has the same element as $title2
at the same index. So if you have two arrays
['a', 'b'], ['b', 'a']
It checks if 'A' == 'B'
and then if 'B' == 'A'
.
What you need to do is something like:
for ($j = 0; $j < count($title1); $j++) {
for ($k = 0; $k < count($title2); $k++) {
if(strtoupper($title2[$k]) == strtoupper($title1[$j]))
{
echo 'Yes<br/>';
echo $title2[$j].'==='.$title1[$j].'<br/>';
}
else {
echo 'No<br/>';
}
}
}
Upvotes: 0
Reputation: 7653
First problem is that you are using <= instead of <. If you are looping through array count and you are using <= it will go over the array bounds. If your array contains 4 elements, the last array value is at index 3: $arr[3]
(fourth position) but you are trying to get the value on $arr[4]
at the last iteration which would cause error. You should check your error_log.
Try this:
$res = count($title1);
for ($j = 0; $j < $res; $j++) {
//you need to check to see if $j'th position is available in $title2 array
if(isset($title2[$j]) && strtoupper($title2[$j]) == strtoupper($title1[$j]))
{
echo 'Yes<br/>';
echo $title2[$j].'==='.$title1[$j].'<br/';
}
else{
echo 'No<br/>';
}
}
Alternatively you could use foreach
loop:
foreach($title1 as $key => $value) {
if (isset($title2[$key]) &&
strtoupper($title2[$key]) == strtoupper($title1[$key])) {
echo 'Yes<br/>';
echo $title2[$key].'==='.$title1[$key].'<br/';
}
else {
echo 'No<br/>';
}
}
Upvotes: 0