just need the explanation - php

In the following code, without == 0 the result shows a wrong answer (A is an odd number). and with == 0 the result shows the correct answer. I need to know the explanation.
<?php
$A = 78;
if ($A % 2 == 0) {
echo "A is a even number";
} else {
echo "A is an odd number";
}
;

Without "==0" i.e.
if($A % 2)
evaluates to 0 becomes,
if(0)
as this is false the respective else is get executed gives you "A is an odd number".

The number 0 is evaluated as false in PHP. In this case $A % 0 is 0.
In that context:
if ($A%0) //this is false, because it is 0 and 0 is evaluated as false
On the other hand, A%2 == 0 is the same as (0 == 0) and that is a true statement.
Other things that are evaluated to false include, but are not limited to: null, an empty array, an empty string an object with no variables.

Related

preg_match always returns 0

In the code below I control if the id in the database is a number. My problem is: the regular expression where I test the id always gives the nummber 0 back never 1 - even when the id is a number.
Can you help me to solve this?
This is the code with the problem:
$muster = "|^[0-9]+$|";
if(preg_match($muster, $_POST["Anzahl"]) == 0 || preg_match($muster, $_POST["id"]) == 0 || $_POST["Anzahl"] < 1) {
die("<a href='javascript:history.back()'>Eingabe überprüfen</a>");
}
I would use PHPValidate filters
Its easier and more convenient:
<?php
$str = "100";
if (filter_var($str, FILTER_VALIDATE_INT)) {
echo("Variable is an integer");
} else {
echo("Variable is not an integer");
}
?>
If filter_var(($str, FILTER_VALIDATE_INT)) is successful it will return 100 as integer, otherwise false
Btw there are many usefull filter: http://php.net/manual/de/filter.filters.validate.php

php short syntax understanding ($z++ % 2) ? "a" : "b";

Newbie here, and i don't know what means ($z++ % 2) ? "a" : "b"; in php and this code gives me the next warning in an old code
PHP message: PHP Warning: A non-numeric value encountered in
$z++ means increase value of $z after use
$z++ % 2 means give me a remainder of $z/2, and increase $z after
If $z%2 == 0, you get b, if $z%2 == 1, you get a
Warning shows because $z is undeclared before. Please add before your code this line:
$z = 0;
$z = 5;
echo ($z++ % 2) ? "a" : "b";
(5%2) = 1 = true
=> a printed
then z became 6
This code evaluates to "a" when $z is odd and "b" when $z is even and then increments $z by one.
$z++ increments $z by one, but only AFTER using it in the expression (note that the PHP manual states that the order of evaluation is undefined and therefore could change between versions. See example 2.)
% 2 modulo 2 (will be 1 if odd, 0 if even)
? : is the ternary operator
When $z is odd ($z++ % 2) == 1 which evaluates to true and the result will be "a".
When $z is even ($z++ % 2) == 0 which evaluates to false and the result will be "b".
The warning is probably because $z is undeclared or not a number (e.g. a string) when this code executes. The % and ++ operators are only valid for numbers.
($z++ % 2) ? "a" : "b"; this is the shorthand version of If/Else (: and ? call as Ternary Operators )it works like this
if($z++ % 2){
"a"
}
else{
"b"
}
$z++ increment the existing value of $z from 1
% gives the remain value after it divide from 2.
If the argument ($z++ % 2) gives any value It executes If("a").
It executes else part("b") if it gives 0.
Example 1:
$z=10;
($z++ % 2)
(5+1 % 2)
(6 % 2)
(0)
result is 0 then do b
Read this for more information: link operators
Happy Coding :)

How to check if a number (float or integer) is within a range (0 - 100)

I'm looking for the fastest way to get this test.
So functions, operands and everything else is allowed.
I tried with the following regex (I'm not an expert):
0\.[0-9]+|100\.0+|100|[1-9]\d{0,1}\.{0,1}[0-9]+
It works except that it erroneously accept 0.0 or 0.000000 and so on.
Also it's not the most appropriated and fastest way.
(if anybody wants to fix the regex to don't allow those 0.00 values it would be appreciated)`
No need for regex:
if (is_numeric($val) && $val > 0 && $val <= 100)
{
echo '$val is number (int or float) between 0 and 100';
}
Demo
Update
It turns out you're getting the numeric values from a string. In that case, it would be best to extract all of them using a regex, something like:
if (preg_match_all('/\d+\.?\d*/', $string, $allNumbers))
{
$valid = [];
foreach ($allNumbers[0] as $num)
{
if ($num > 0 && $num <= 100)
$valid[] = $num;
}
}
You can leave out the is_numeric check, because the matched strings are guaranteed to be numeric anyway...
Use bccomp
This is a perfect use case for BCMath functions.
function compare_numberic_strings($number) {
if (
is_numeric($number) &&
bccomp($number, '0') === 1 &&
bccomp($number, '100') === -1
) {
return true;
}
return false;
}
echo compare_numberic_strings('0.00001');
//returns true
echo compare_numberic_strings('50');
//returns true
echo compare_numeric_strings('100.1');
//returns false
echo compare_numeric_strings('-0.1');
//returns false
From the manual:
Returns 0 if the two operands are equal, 1 if the left_operand is
larger than the right_operand, -1 otherwise.
I think your regex pattern should look like this:
^\d{1,2}$|(100)
Demo

String comparison is not working in php

I'm very new to php. I have a json named json. When I try to do this:
echo $json->status;
I get :
CREATED
I try to compare this result with normal string CREATED like this:
if(strcasecmp("CREATED",$json->status))
{
print_r("Order created successfuly");
}
but for some reason the if condition is not evaluting to true. Even though I compare CREATED with CREATED!
Not sure where the error is.
Thanks in advance.
This function return zero if strings are equal
if (strcasecmp("CREATED",$json->status) == 0)
Look to the manual:
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
so strcasecmp('a','a') is 0, therefore you have to change your code into
if(strcasecmp("CREATED",$json->status) == 0)
{
print_r("Order created successfuly");
}
http://php.net/manual/en/function.strcasecmp.php
Quote from the page :
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
So strcasecmp('CREATED', 'CREATED') returns 0. And 0 is not equals to true.
You must do that :
if (strcasecmp("CREATED",$json->status) === 0) {
print_r("Order created successfuly");
}
if (strcasecmp( $json->status, "CREATED") == 0)
{
...
...
}
Why cant you just use a simpler if statement?
if( $json->status == "CREATED" ) {
print_r("Order created successfuly");
}
And check for whitespaces at the end or start of the status.
To compare strings, try to do the following :
if($json->status == "CREATED")
{
echo "Order created successfuly";
}

Best way to check for positive integer (PHP)?

I need to check for a form input value to be a positive integer (not just an integer), and I noticed another snippet using the code below:
$i = $user_input_value;
if (!is_numeric($i) || $i < 1 || $i != round($i)) {
return TRUE;
}
I was wondering if there's any advantage to using the three checks above, instead of just doing something like so:
$i = $user_input_value;
if (!is_int($i) && $i < 1) {
return TRUE;
}
Not sure why there's no suggestion to use filter_var on this. I know it's an old thread, but maybe it will help someone out (after all, I ended up here, right?).
$filter_options = array(
'options' => array( 'min_range' => 0)
);
if( filter_var( $i, FILTER_VALIDATE_INT, $filter_options ) !== FALSE) {
...
}
You could also add a maximum value as well.
$filter_options = array(
'options' => array( 'min_range' => 0,
'max_range' => 100 )
);
Learn more about filters.
the difference between your two code snippets is that is_numeric($i) also returns true if $i is a numeric string, but is_int($i) only returns true if $i is an integer and not if $i is an integer string. That is why you should use the first code snippet if you also want to return true if $i is an integer string (e.g. if $i == "19" and not $i == 19).
See these references for more information:
php is_numeric function
php is_int function
The best way for checking for positive integers when the variable can be INTEGER or STRING representing the integer:
if ((is_int($value) || ctype_digit($value)) && (int)$value > 0 ) { // int }
is_int() will return true if the value type is integer. ctype_digit() will return true if the type is string but the value of the string is an integer.
The difference between this check and is_numeric() is that is_numeric() will return true even for the values that represent numbers that are not integers (e.g. "+0.123").
It's definitely heading towards the land of micro-optimisation, but hey: the code I'm working on chews through millions of items every day and it's Friday. So I did a little bit of experimenting...
for ($i = 0; $i < 1000000; $i++) {
// Option 1: simple casting/equivalence testing
if ((int) $value == $value && $value > 0) { ... }
// Option 2: using is_int() and ctype_digit(). Note that ctype_digit implicitly rejects negative values!
if ((is_int($value) && $value > 0) || ctype_digit($value)) { ... }
// Option 3: regular expressions
if (preg_match('/^\d+$/', $value)) { ... }
}
I then ran the above tests for both integer and string values
Option 1: simple casting/equivalence testing
Integer: 0.3s
String: 0.4s
Option 2: using is_int() and ctype_digit()
Integer: 0.9s
String: 1.45s
Option 3: regular expressions
Integer: 1.83s
String: 1.60s
Perhaps unsurprisingly, option 1 is by far the quickest, since there's no function calls, just casting. It's also worth noting that unlike the other methods, option 1 treats the string-float-integer value "5.0" as an integer:
$valList = array(5, '5', '5.0', -5, '-5', 'fred');
foreach ($valList as $value) {
if ((int) $value == $value && $value > 0) {
print "Yes: " . var_export($value, true) . " is a positive integer\n";
} else {
print "No: " . var_export($value, true) . " is not a positive integer\n";
}
}
Yes: 5 is a positive integer
Yes: '5' is a positive integer
Yes: '5.0' is a positive integer
No: -5 is not a positive integer
No: '-5' is not a positive integer
No: 'fred' is not a positive integer
Whether or not that's a good thing for your particular use-case is left as an exercise for the reader...
The other best way to check a Integer number is using regular expression. You can use the following code to check Integer value. It will false for float values.
if(preg_match('/^\d+$/',$i)) {
// valid input.
} else {
// invalid input.
}
It's better if you can check whether $i > 0 too.
preg_match('{^[0-9]*$}',$string))
and if you want to limit the length:
preg_match('{^[0-9]{1,3}$}',$string)) //minimum of 1 max of 3
So pisitive int with a max length of 6:
if(preg_match('{^[0-9]{1,6}$}',$string)) && $string >= 0)
You don't really need to use all three check and if you want a positive integer you might want to do the opposite of what is in your code:
if(is_numeric($i) && $i >= 0) { return true; }
Check Sören's answer for more information concerning the difference between is_int() and is_numeric()
if(preg_match('/^[1-9]\d*$/',$i)) {
//Positive and > 0
}
Rather than checking for int OR string with multiple conditions like:
if ( ctype_digit($i) || ( is_int($i) && $i > 0 ) )
{
return TRUE;
}
you can simplify this by just casting the input to (string) so that the one ctype_digit call will check both string and int inputs:
if( ctype_digit( (string)$i ) )
{
return TRUE;
}
In addition to all the other answers: You are probably looking for ctype_digit. It looks for a string containing only digits.
Definition:
!A = !is_numeric($i)
B = $i < 1
!C = $i != round($i)
Then...
!is_numeric($i) || $i < 1 || $i != round($i) is equal to
!A || B || !C
So:
!A || B || !C = !A || !C || B
Now, using the deMorgan theorem, i.e. (!A || !C) = (A && C), then:
!A || !C || B = (A && C) || B
Now, note that A && C = is_numeric($i) && $i == round($i), but if $i == round($i) is TRUE, then is_numeric($i) is TRUE as well, so we can simplify A && C = C so,
(A && C) || B = C || B =
$i == round($i) || $i < 1
So you just need to use:
$i = $user_input_value;
if ($i == round($i) || $i < 1) {
return TRUE;
}
Laravel 4.2 Validation rule for positive number
It takes only positive numbers including float values.
public static $rules = array(
'field_name' => 'required|regex:/^\d*\.?\d*$/'
);
e.g:20,2.6,06
The first example is using round to verify that the input is an integer, and not a different numeric value (ie: a decimal).
is_int will return false if passed a string. See the PHP manual examples for is_int
To check for positive integer use:
$i = $user_input_value;
if (is_int($i) && $i > 0) {
return true; //or any other instructions
}
OR
$i = $user_input_value;
if (!is_int($i) || $i < 1) {
return false; //or any other instructions
}
Use the one that fits your purpose as they are the same. The following examples demonstrate the difference between is_numeric() and is_int():
is_numeric(0); // returns true
is_numeric(7); // returns true
is_numeric(-7); // returns true
is_numeric(7.2); // returns true
is_numeric("7"); // returns true
is_numeric("-7"); // returns true
is_numeric("7.2"); // returns true
is_numeric("abc"); // returns false
is_int(0); // returns true
is_int(7); // returns true
is_int(-7); // returns true
is_int(7.2); // returns false
is_int("7"); // returns false
is_int("-7"); // returns false
is_int("7.2"); // returns false
is_int("abc"); // returns false
All these answers overlook the fact that the requestor may checking form input.
The is_int() will fail because the form input is a string.
is_numeric() will be true also for float numbers.
That is why the $i == round($i) comes in as it checks for the input being a whole number.
Ok, I know this thread is really old but I share #Jeffrey Vdovjak's opinion: since I was able to find it, it might still help someone else out there.
php's gmp_sign() might be another easy way to check. It works for integer and numeric strings, and returns 1 if a is positive, -1 if a is negative, and 0 if a is zero.
So:
// positive
echo gmp_sign("500") . "\n";
// negative
echo gmp_sign("-500") . "\n";
// zero
echo gmp_sign("0") . "\n";
will output:
1
-1
0
See function manual at http://php.net/manual/en/function.gmp-sign.php
P.S. You'll need to have php_gmp.dll enabled in your .ini file.
This's my solution, hope helpful :
if (is_numeric($i) && (intval($i) == floatval($i)) && intval($i) > 0)
echo "positive integer";
i check if string is numeric, second check to sure it's integer and third to sure it positive
If you use "is_int" the variable must be integer, so it can't be a float value. (no round needed).
if(isset($i) && is_int($i) && $i >= 0){ //0 is technically a postive integer I suppose
return TRUE; //or FALSE I think in your case.
}
I would do something like this:
if ((int) $i > 0) {
// this number is positive
}
The number gets typecast to a positive or negative number depending on the minus sign being at the front. Then compares the typecast number to being greater than 0 to determine if the number is positive.

Categories