字符串和数组不像我想的那样工作

She*_*Pro 0 php arrays string

我正在尝试更多地了解字符串和数组.我有这段代码:

<?php
$states = "OH, VA, GA";
$arrayStates = explode(",", $states);
$exists = "GA";
print_r($arrayStates);

if (in_array($exists, $arrayStates)){
    echo "<br/>" . $exists . " " . "exists.";
} else {
    echo "<br/>" . $exists . " " . "doesn't exist.";
}
?>
Run Code Online (Sandbox Code Playgroud)

根据我的软弱思想,GA应该存在于数组中.如果我把$ exists ="OH",那就行了.但屏幕显示:

Array ( [0] => OH [1] => VA [2] => GA ) 
Run Code Online (Sandbox Code Playgroud)

GA不存在.

我在这里不理解什么?

Bar*_*mar 5

该数组包含" GA"一个空格作为第一个字符的字符串.这不等于"GA",它没有空间.

您应该使用explode(", "), $states)或调用trim()数组的每个元素:

$arrayStates = array_map('trim', explode(",", $states));
Run Code Online (Sandbox Code Playgroud)