简体   繁体   English

substr前两个字母匹配数组不起作用

[英]substr first two letters match in array not working

I have a string which is being generated from an input field and i want to check the first two characters and see if they are found in an array. 我有一个从输入字段生成的字符串,我想检查前两个字符,看看是否在数组中找到它们。 If they are I want a message to appear. 如果他们是我希望出现一条消息。

Can anyone explain why this isn't working please? 谁能解释为什么这行不通?

$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";
    }   
}

Your usage of in_array is wrong. 您使用的in_array错误。 Change 更改

if(substr($i, 0, 2) === in_array($i, $ep)) {
  echo "Sorry we don't deliver to your postcode";
}   

to

if(in_array(substr($i, 0, 2), $ep)) {
  echo "Sorry we don't deliver to your postcode";
}   

You misunderstand how in_array works, check the manual for more details. 您误解了in_array工作原理,请查看手册以获取更多详细信息。

The following code is an improved way to check if the given post code is valid 以下代码是检查给定邮政编码是否有效的改进方法

<?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";
    }
}

Use it like this: 像这样使用它:

$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";
    }   
}

Try this: 尝试这个:

if(in_array(substr($i, 0, 2), $ep)) {
    echo "Sorry we don't deliver to your postcode";
}  

Try it like this: 像这样尝试:

$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";
    }   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM