How to compare 2 variable using php like this? - php

How to compare 2 variable using php like this ?
$aaa = "1234567890qwertyuiopsdflkjwerouioiuweewjkee";
$bbb = "1234567890qwertyuiop";
How to check
if(first char to twenty char of $aaa == $bbb)
{ echo "same"; }
else
{ echo "not same"; }

I assume you are searching for strncmp:
This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison.
if(strncmp($aaa, $bbb, 20) == 0) {
# First twenty characters match.
} else {
# First twenty characters don't match.
}

$aaafirst20 = $small = substr($aaa, 0, 20);
if(strcmp($aaafirst20 , $bbb){
}
else{
}

Try this :
You can use strcmp function for the same.
PHP docs # strcmp
if(strcmp($aaa,$bbb)){
echo "same";
} else {
echo "not same";
}

You can use strpos() to check if $bbb is found in $aaa, and starts at position 0.
if (strpos($aaa, $bbb) === 0) {
echo 'Same';
}
else echo 'Not same';
See demo

Your exact solution would be
// first reduce a to its first 20 characters
$trimmed = substr($aaa, 0, 20);
// now compare with b
if($trimmed == $bbb){
// same
}
Or, all in one line
if(substr($aaa, 0, 20) == $bbb){
// same
}

Related

Compare first 4 characters of a string PHP

The problem is with this line:
if $var LIKE '1800%';
and I'm not sure how to fix it. Thanks.
<?php
//check to see if account number is like 1800*
if (isset($_POST['acct_number'])) {
$var = $_POST['acct_number'];
if $var LIKE '1800%'; {
//stop the code
exit;
} else {
echo 'normal account number';
}
}
?>
You need PHP not MySQL. For 1800% just check that it is found at position 0:
if(strpos($var, '1800') === 0) {
//stop the code
exit;
} else {
echo 'normal account number';
}
If it can occur anywhere like %1800% then:
if(strpos($var, '1800') !== false) {
//stop the code
exit;
} else {
echo 'normal account number';
}
Use substr function to get first 4 characters and compare it with 1800.
if(substr($var, 0, 4) == '1800')
{
// your code goes here.
}
``
Another way could be to use strpos()
if (strpos($var, '1800') === 0) {
// var starts with '1800'
}
I would use a regular expression for this preg_match('/^1800.+/', $search, $matches);

Why substr() doesn't work correctly with a number that has a leading zero?

I have this script:
function DecryptId($id) {
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = 014;
echo DecryptId($id);
//=> no
Demo
Why it prints no? I expect it prints yes. Because the value of $id starts with 0. What's wrong?
EDIT: In reality I'm passing $id like this: DecryptId($_POST['au']);. $_POST['au'] is containing a number. Something like these:
23
43552
0153
314
09884
As you see, sometimes that number starts with 0. And I need to pass it as a string. How can I do that?
Because of the leading zero, PHP will be parsing that number as octal. Even if it didn't do this, most languages will strip off the leading zeros (since they don't actually form part of the number). This means that $id will evaluate to 12.
Are you sure you don't want to declare it as a string? ($id = "014")
Your function is working fine the issue is that you are passing a number in your function when you should provide a string. So in the case that your variable type is integer the leading zero will eventually fly away.
You can add something to your function to check the variable type and inform the user.
function DecryptId($id) {
$type = gettype( $id );
if($type!= "string") {
echo "Your variable has type ".$type.". Use a 'string' type variable";
return;
}
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = 014;
echo DecryptId($id);
echo "\n";
$id = '014';
echo DecryptId($id);
Try the above example in PHP Sandbox
try this
<?php
function DecryptId($id) {
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}
$id = '014';
echo DecryptId($id);
?>

Validate numeric value but exclude hex or sci notation

I used to rely on is_numeric() for making sure data passed from users is numeric. I recently discovered that users can also pass data 0xFF (hexdec = 255).
I'd like to disallow anything that is not a whole number (and not a hex representation).
Here's what I've tried so far.
$i_haxors_u = $_GET['id'];
$regex = '/[0-9]*/';
if (!empty($i_haxors_u) && !preg_match($regex, $i_haxors_u))
{
echo '<p>Invalid $i_haxors_u ' . strip_tags($i_haxors_u);
} else {
echo '<p>$i_haxors_u is numeric... maybe.';
}
This is still giving values like 0xFF a pass. How do I allow non-hex numbers only?
UPDATE Nov 12 2014.
Note that the selected answer works fine for data passed via GET, but will not work if a variable is set to a hex value.
$x = 0xFF;
if (is_numeric($x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
if (preg_match('/^[\d]+$/',$x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
$x = '0xFF';
if (is_numeric($x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
if (preg_match('/^[\d]+$/',$x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
Prints
255 is a number.
255 is a number.
0xFF is a number.
0xFF is not a number.
use match non-digit in your regex: $regex = '/\D/';
assume failure and pass when confirming that no non-digits are present in the input.
following code succeeds on id =7, give fail on id = 7.2, 7.2x, ffff, 0xff, -1
$id = $_GET['id'];
//assuming failure:
$valid = false;
if (!preg_match('/\D/',$id)) { $valid = true; } //fail if containing non-digit
if ($valid) {
echo "$id provided is valid";
}
else {
echo "$id provided is not valid";
}
You need to use anchors and use + quantifier to only allow integers:
$regex = '/^\d+$/';
Using + quantifier will also let you take out !empty($i_haxors_u) condition since \d+ will enforce 1 or more digits.
It's just because you have to test all the number:
$regex = '/^[0-9]+$/';
no need to test empty with +

check if numeric php

my problem is, i have a form which i fill blabla and after i submit i need to check if the var '$number' contains only 9 numbers. which means that if it contains at least 1 letter or has less or more than 9 length it should return false, else it should return true;
this is what i got so far:
if (!is_numeric ($number) {
//do
} else {
}
1st problem: This code should take care of the only numbers part but it doesnt, it always returns false.
2nd: do you guys know of any way to take care of the 9 digits only verification?
thanks and sorry for my bad english, not my native language :P
Your number may contain unwanted whitespaces which cause the is_numeric() test not to work properly
So do the following: $number = trim($number); to remove them.
Then indeed this snippet is good to check if your variable is a number:
if (!is_numeric ($number)) {
//do
} else {
}
And for the number digits do a if statement to see if your number is between 100000000 and 999999999
So the full code will be:
$number = trim($number);
if (!is_numeric ($number)) {
//do
} else {
if ($number >= 100000000 && $number <= 999999999) {
// Everything is ok
} else {
}
}
Didn't understood your complete question coz of you native language :p, but i think you want this:
if (is_numeric($number) {
if(strlen($number) == 9){
return true;
} else {
return false;
}
} else {
echo 'Not a number';
}
Check if it contains digits and check whether its exactly contains 9.
$number = '123456789';
if(!preg_match('/^\d{9}$/', $number)) {
echo 'not ok';
} else {
echo 'ok';
}

Detecting negative numbers

I was wondering if there is any way to detect if a number is negative in PHP?
I have the following code:
$profitloss = $result->date_sold_price - $result->date_bought_price;
I need to find out if $profitloss is negative and if it is, I need to echo out that it is.
if ($profitloss < 0)
{
echo "The profitloss is negative";
}
Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.
In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:
$turnover = 10000;
$overheads = 12500;
$difference = abs($turnover-$overheads);
echo "The Difference is ".$difference;
This would produce The Difference is 2500.
I believe this is what you were looking for:
class Expression {
protected $expression;
protected $result;
public function __construct($expression) {
$this->expression = $expression;
}
public function evaluate() {
$this->result = eval("return ".$this->expression.";");
return $this;
}
public function getResult() {
return $this->result;
}
}
class NegativeFinder {
protected $expressionObj;
public function __construct(Expression $expressionObj) {
$this->expressionObj = $expressionObj;
}
public function isItNegative() {
$result = $this->expressionObj->evaluate()->getResult();
if($this->hasMinusSign($result)) {
return true;
} else {
return false;
}
}
protected function hasMinusSign($value) {
return (substr(strval($value), 0, 1) == "-");
}
}
Usage:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));
echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :(";
Do however note that eval is a dangerous function, therefore use it only if you really, really need to find out if a number is negative.
:-)
if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == "-")
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
if ( $profitloss < 0 ) {
echo "negative";
};
Don't get me wrong, but you can do this way ;)
function nagitive_check($value){
if (isset($value)){
if (substr(strval($value), 0, 1) == "-"){
return 'It is negative<br>';
} else {
return 'It is not negative!<br>';
}
}
}
Output:
echo nagitive_check(-100); // It is negative
echo nagitive_check(200); // It is not negative!
echo nagitive_check(200-300); // It is negative
echo nagitive_check(200-300+1000); // It is not negative!
Just multiply the number by -1 and check if the result is positive.
You could use a ternary operator like this one, to make it a one liner.
echo ($profitloss < 0) ? 'false' : 'true';
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers:
http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
Can be easily achieved with a ternary operator.
$is_negative = $profitloss < 0 ? true : false;
I wrote a Helper function for my Laravel project but can be used anywhere.
function isNegative($value){
if(isset($value)) {
if ((int)$value > 0) {
return false;
}
return (int)$value < 0 && substr(strval($value), 0, 1) === "-";
}
}

Categories