我有一个从输入字段生成的字符串,我想检查前两个字符,看看它们是否在数组中找到。如果他们是我想要一条消息出现。
任何人都可以解释为什么这不起作用吗?
$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";
}
}
答案 0 :(得分:2)
您对in_array的使用是错误的。改变
if(substr($i, 0, 2) === in_array($i, $ep)) {
echo "Sorry we don't deliver to your postcode";
}
到
if(in_array(substr($i, 0, 2), $ep)) {
echo "Sorry we don't deliver to your postcode";
}
答案 1 :(得分:2)
您误解了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";
}
}
答案 2 :(得分:1)
像这样使用:
$i = strtoupper($_POST['postcode']);
$ep = array("AB", "BT", "GY", "HS", "IM", "IV", "JE", "PH", "KW");
if (isset($i)) {
$i = substr($i, 0, 2);
if(in_array($i, $ep)) {
echo "Sorry we don't deliver to your postcode";
}
}
答案 3 :(得分:1)
试试这个:
if(in_array(substr($i, 0, 2), $ep)) {
echo "Sorry we don't deliver to your postcode";
}
答案 4 :(得分:0)
试试这样:
$i = strtoupper($_POST['postcode']);
$ep = array("AB", "BT", "GY", "HS", "IM", "IV", "JE", "PH", "KW");
if (isset($i)) {
$i = substr($i, 0, 2);
if(in_array($i, $ep)) {
echo "Sorry we don't deliver to your postcode";
}
}