Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 字符串和数组不像我想的那样工作_Php_Arrays_String - Fatal编程技术网

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

Php 字符串和数组不像我想的那样工作,php,arrays,string,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 "<

我试图学习更多关于字符串和数组的知识。我有一段代码:

<?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.";
}
?>
GA不存在


我在这里不明白什么?

你需要在逗号后加一个空格

$arrayStates = explode(", ", $states);

数组包含以空格作为第一个字符的字符串GA。这不等于“GA”,它没有空格

应在数组的每个元素上使用explode$states或调用trim:

$arrayStates = array_map('trim', explode(",", $states));
您正在使用拆分,但文本中有空格,因此拆分后您有:

$arrayStates[0] stores "OH"
$arrayStates[1] stores " VA"
$arrayStates[2] stores " GA"
数组[0]=>OH[1]=>\u VA[2]=>\u GA

您可以按拆分,或用空格替换下划线

也可以在分割后修剪所有值,如:


foreach$arrayStates为$k=>$v$arrayStates[$k]=trim$v

这是因为它被除以,所以数组内容是:

Array
(
    [0] => OH
    [1] =>  VA
    [2] =>  GA
)

您需要执行$arrayStates=explode,$states

explode方法仅拆分逗号上的字符串,不删除空格。因此,您最终会将$exists与数组内部的GA进行比较,请注意应用explode后$arrayStates中的空格=]

。。。你有:

$arrayStates[0] stores "OH"
$arrayStates[1] stores " VA"
$arrayStates[2] stores " GA"

注意:在索引2中,数组存储的是GA,注意空格而不是GA,这是因为在使用的explode函数中,。要使您的代码按您希望的方式工作,您应该在explode函数中使用,请注意空格

使用var_dump进行调试。当人们编辑我的代码时-他们如何显示颜色?使用{}代码工具标记您的代码。哦。哈哈。真的很快,因为我不清楚-第二个逗号是什么?我真的不确定它的用途是什么。@SherwoodPro如果我们讨论的是同一个逗号,它会分隔传递给分解函数的参数。从技术上讲,逗号后面不需要空格,但如果需要的话看起来会更好。我想我应该补充一下你的解释:他的回音看起来是正确的,因为HTML只显示一个键入的空格,除非你在变量$states是记录集的情况下添加,比如$states=$row_getStates['states'];。也会有空间吗?或者爆炸不需要空间吗?我不确定我是否理解这个问题。变量的名称无关紧要。您是否在询问如果从数据库中读取值,是否会发生这种情况?在这种情况下,它取决于数据库中的内容。