开发者

Why do two array values look the same, but don't evaluate as equal?

开发者 https://www.devze.com 2022-12-27 13:20 出处:网络
When I compare two array values I see two strings that look the same.php doesn\'t agree. $array1 = array(\'address\'=>\'32 Winthrop Street\',\'state\'=>\'NY\');

When I compare two array values I see two strings that look the same. php doesn't agree.

$array1 = array('address'=>'32 Winthrop Street','state'=>'NY');
$array2 = array('address'=>'32 Winthrop Street');

$results = array_diff_assoc($array1, $array2);

var_dump($results) 
//ec开发者_如何学Gohos ['address'] => string(18) "32 Winthrop Street" ['state']=>'NY'

Why is this?

EDIT Be advised that this isn't the actual code I'm testing, I've simplified code to illustrate my question, which is about strings being equal, not whether or not this code will run.


First: your code will not even run but die in a syntax error at line 2. Here's the corrected version:

<?php
$array1 = array ('address'=>'32 Winthrop Street','state'=>'NY');
$array2 = array ('address'=>'32 Winthrop Street');

$results = array_diff_assoc($array1, $array2);

var_dump($results); 

Second: I tested this with PHP 5.2.12 and 5.3.1 and it works. It echoes:

array(1) {
  ["state"]=>
  string(2) "NY"
}

It's really just full of incorrect syntax. That's all.


Make sure your input arrays really look like that. If you're echoing data in your browser, you might miss whitespace. '32 Winthrop Street' is not the same as ' 32 Winthrop Street', for example. The same is true for your array keys.

You could $array1 = array_map('trim', $array1) and $array2 = array_map('trim', $array2) to remove leading and trailing whitespace from the values. See if that makes any difference?

You can check if they're really the same by checking if ($array1['address'] === $array2['address']). If that evaluates to false, there's a difference, you're just not seeing it (see binaryLV's answer for elaboration on a possible cause). If it evaluates to true, you might want to take a closer look at the array keys.


Are the values hard-coded or from some other source? What does var_dump($array1['address'], $array2['address']) give? Maybe there are some "invisible" spaces somewhere?


$array1 = ('address'=>'32 Winthrop Street','state'=>'NY');
$array2 = ('address'=>'32 Winthrop Street');

$results = array_diff_assoc($array1, $array2); // remove the ' on this line 

The ' is probably confusing the PHP engine into thinking it's a string... then add insult to injury you don't close the "string".

Looks like a typo to me.

0

精彩评论

暂无评论...
验证码 换一张
取 消