php - substr 前两个字母在数组中匹配不起作用

标签 php arrays

我有一个从输入字段生成的字符串,我想检查前两个字符并查看是否在数组中找到它们。如果是,我希望显示一条消息。

谁能解释为什么这不起作用?

$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 - substr 前两个字母在数组中匹配不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48805452/

相关文章:

php - 将变量追加到 mysql 表数据中

php - 从 DIV 创建图像

c++ - 使用 "Sort K number of elements based array"算法的数组中的第 K 个最大数

javascript - 如果值在数组中,则设置属性值

java - 将数组中的两个 double 相乘时收到 0.0

php - 使用 === '' 检查空字符串不起作用

php - 与 PHP 的 SSH 连接

php - 无法使用 exec 命令来使用 ffmpeg

java - 在应用程序购买中工作,但方法未执行?

c# - 在数组中使用 Person 类