Adam Alvey
Adam Alvey

Reputation: 11

New to PHP, need to ignore part of a variable in a function

So I'm attempting to concatenate two integers that form a whole serial number to verify if a user has the correct serial code. My second variable will always begin with P, how would I ignore the P from a user input while still having it appear in the concatenated variables in a function like this?

$a = '1800';
$b = P100000000;

if ($a >= "1800" && $b >= "100000000") {
    echo "$a-$b is correct";
  } else {
      echo "I'm sorry, that serial does not match our system.";
}

Upvotes: 0

Views: 300

Answers (4)

d g
d g

Reputation: 1604

Could also use regex if you have multiple non-digit beginning character;

<?php

$a = '1800';
$b = P100000000;

$b = preg_replace('/^\D/', '', $b);
print("${b}\n");

Upvotes: 0

SirPilan
SirPilan

Reputation: 4857

<?php
$a = 1800; // no quotes here for a number
$b = 'P100000000'; // quotes here please
$real_b = (int)substr($b,1); // cut the first letter, then cast to int

if ($a >= 1800 && $real_b >= 100000000) { // no quotes here for numbers or its a string
    echo "$a-$b is correct";
  } else {
      echo "I'm sorry, that serial does not match our system.";
}

Upvotes: 0

Ice76
Ice76

Reputation: 1130

Another way to remove all non-numeric characters from a string and convert it to an integer for comparison would be something like:

intval( filter_var( $b, FILTER_SANITIZE_NUMBER_INT ) )

the filter_var function returns a string, and the intval function returns the integer value from a string.

Upvotes: 0

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

One way is to use ltrim.

if ($a >= "1800" && ltrim($b, 'P') >= "100000000") { ...

If the P isn't there for some reason, it won't remove anything.

Upvotes: 3

Related Questions