Reputation: 6471
I have an array ($name_new
) that is created by a text file:
foreach ($properties as $key => $row) {
$name_new[] = $row['name'];
}
Here is the result for $name_new
:
array(2) {
[0]=>
string(32) "john"
[1]=>
string(32) "frank"
}
And another array I am creating from the mySQL database:
$sql = "SELECT * FROM data;
$p = $pdo->prepare($sql);
$p->execute();
foreach ($pdo->query($sql) as $row) {
$name_orig[] = $row['name'];
}
Here is the result for $name_orig
:
array(2) {
[0]=>
string(32) "john"
[1]=>
string(32) "sam"
}
I am comparing those two arrays:
if ($name_new != $name_orig) {
$name_result = array_diff_assoc($name_orig, $name_new);
foreach($name_result as $r){
echo "This name is not matching: ".$r;
}
}
So my result here is:
This name is not matching: sam
My problem is, that I would also need the key for the name in my result. But this key only exists in the text file.
So if I write this:
foreach ($properties as $key => $row) {
$name_new[$key] = $row['name'];
}
Here is the result for $name_new[$key]
...
array(2) {
["123"]=>
string(32) "john"
["456"]=>
string(32) "frank"
}
... I get the key. But how can I connect this key to my result sam
The result I would need is
This name is not matching sam (Key: 456)
Upvotes: 2
Views: 52
Reputation: 789
Please improve below code
if ($name_new != $name_orig) {
$name_result = array_diff_assoc($name_orig, $name_new);
foreach($name_result as $k=> $r){
echo "This name is not matching: ".$r." and key:".$k;
}
}
Hope this works
Upvotes: 3
Reputation: 4298
when comparing both arrays, just adding the index along to your foreach loop should do the trick:
foreach($name_result as $k => $r){
echo "This name is not matching: ".$r. "(Key:".$k.")";
}
Upvotes: 1