我有一个从输入字段生成的字符串,我想检查前两个字符,看看是否在数组中找到它们。如果他们是我希望出现一条消息。
谁能解释为什么这行不通?
$i = strtoupper($_POST['postcode']);
$ep = array("AB", "BT", "GY", "HS", "IM", "IV", "JE", "PH", "KW");
if (isset($i)) {
if(substr($i, 0, 2) === in_array($i, $ep)) {
echo "Sorry we don't deliver to your postcode";
}
}
参考方案
您误解了in_array
的工作原理,请查看manual以获取更多详细信息。
以下代码是检查给定邮政编码是否有效的改进方法
<?php
/**
* Check if the given post code is valid
* @param string $postcode
* @return boolean
*/
function is_valid_postcode( $postcode = '' )
{
$ep = array("AB", "BT", "GY", "HS", "IM", "IV", "JE", "PH", "KW");
$postcode = strtoupper( $postcode );
return in_array( $postcode , $ep );
}
if( isset( $_POST['postcode'] ) ){
// Remove unwanted spaces if they're there
$postcode = trim( $_POST['postcode'] );
// Extract only the first two caracters
$postcode = substr($postcode, 0, 2 );
// Check if the submitted post code is valid
if( !is_valid_postcode( $postcode ) ){
echo "Sorry we don't deliver to your postcode";
}
}
PHP:将数组值加在一起 - php我相信这比标题听起来要难一些,但我可能完全错了。我有一个像这样的数组:[["londrina",15],["cascavel",34],["londrina",23],['tiradentes',34],['tiradentes',21]] 我希望能够采用通用…
PHP JQuery复选框 - php我有以下片段。 var myData = { video: $("input[name='video[]']:checked").serialize(), sinopse: $("#sinopse").val(), dia: $("#dia").val(), quem: $(…
PHP:获取调用引用的数组名称 - php假定以下函数并调用:function doSomething( &$someArray ) { // Do something to $someArray } $names=array("John", "Paul", "George", "Ringo"); doSomet…
PHP-MySQL结果转换为JSON - php我试图了解如何将MySQL结果转换为JSON格式,以便以后可以在Javascript中使用此JSON来构建HTML表。但是我的代码只是产生大量的空值,我还不明白为什么。$result = mysqli_query($con, "SELECT * FROM Customers"); $test = json_encode($result);…
PHP Count数组元素 - php嗨,有人可以解释为什么这会返回“数组由0个元素组成”。 :$arr = array(1,3,5); $count = count($arr); if ($count = 0) { echo "An array is empty."; } else { echo "An array has $count elements.…