I'm trying to get two numbers from a string using substr
function and then convert these into a int using $convert = $numbers+0;
I then want to see if this number is between two numbers set in an array and return true if it is. Can anyone help me please?
$kacodes = array(27, 28);
$postcodearea = "KA21";
$numbers = substr($postcodearea, 2, 2);
$convert = $numbers +0;
if(($kacodes[0] <= $convert) && ($convert <= $kacodes[1])) {
return true;
}
Sorry to be vague!
Please see a better picture of what I'm trying to achieve below. I've found out it works if i manually add the string into the function but when adding it into the if / else statement it seems to skip to the else. If that makes sense?
function postcode_form() {
echo "<form method='post' action=''>
<input id='postcode' name='postcode' type='text'>
<input type='submit' name='button'></button>
</form>";
}
function is_valid_postcode( $postcode = '' )
{
$ep = array("AB", "BT", "GY", "HS", "IM", "IV", "JE", "PH", "KW");
$postcode = strtoupper( $postcode );
return in_array( $postcode , $ep );
}
function is_valid_postcode_area( $postcodearea )
{
$kacodes = array(27, 28);
$pacodes = array(20, 80);
$pocodes = array(30, 41);
$postcodearea = strtoupper( $postcodearea );
if(substr($postcodearea, 0, 2) === "KA") {
$numbers = substr($postcodearea, 2, 2);
$convert = $numbers +0;
var_dump($convert);
if( ($kacodes[0] <= $convert) && ($convert <= $kacodes[1]) ) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
// define the woocommerce_after_single_product_summary callback
function action_woocommerce_after_single_product_summary( $evolve_woocommerce_after_single_product_summary, $int ) {
postcode_form();
if( isset( $_POST['postcode'] ) ){
// Remove unwanted spaces if they're there
$postcode = trim( $_POST['postcode'] );
// Extract only the first two characters
$postcode = substr($postcode, 0, 2 );
$postcodearea = substr($postcode, 0, 4);
// Check if the submitted post code is valid
if( is_valid_postcode( $postcode )){
echo "Sorry we don't deliver to your postcode";
}
elseif(is_valid_postcode_area($postcodearea)) {
echo "Sorry we don't deliver to your postcode";
}
else {
echo "We deliver to your postcode";
}
}
};
I've managed to work out what was causing the problem. I was using the variable $postcode
in $postcodearea
which had already been limited to two characters!
Before
$postcode = trim( $_POST['postcode'] );
// Extract only the first two characters
$postcode = substr($postcode, 0, 2 );
$postcodearea = substr($postcode, 0, 4);
After
$postcoderaw = trim( $_POST['postcode'] );
// Extract only the first two characters
$postcode = substr($postcoderaw, 0, 2 );
$postcodearea = substr($postcoderaw, 0, 4);