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
Related
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.
I have this function:
function return_a_number($source) {
switch ($source) {
case "0&0&0&0":
return 0;
case "0&0&1&1":
return 1;
case "1&1&1&1":
return 2;
}
}
Where $source have an ipotetic number concatenated with &.
How can i return 0 if $source have only '0' characters or 1 if have '0' and '1' characters or 2 if have only '1' characters?
// If there is a 0, ( check if there's also a one -> 1 or 0 ) : else only 1s => 2
return strpos($source, '0') !== false ? ( strpos($source, '1') !== false ? 1 : 0 ) : 2;
You could of course also write a regex, but why make it complicated if it works that simple. You might want to catch an empty string depending on your input.
Here is what the logic in your function should be, easy to understand and covers all three cases. Keep in mind that you must always check for 0 and 1 together first, then do it individually
if (strpos($source, '0') !== false && strpos($source, '1') !== false) {
return 0;
}
elseif (strpos($source, '0') !== false) {
return 1;
}
else {
return 2
}
You can put one more 'elseif' instead of the last 'else' if you might get different result than the 3 outcomes you mentioned
I am new to PHP. My problem is I need the input to validate to a minimum 20 character input and return the last nine. Can anybody tell me if my argument is close to working and if not what do I need to do?
if (!empty($_POST['usen']) ||
strlen($usen['usen'] >= 20 )) {
$switch = substr($usen, -9, 9); // returns last nine of sentence
$output_form=false;
} else {
$error_text .="<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form=true;
}
You have several syntax problems and variable-naming problems. Your code should be:
if (!empty($_POST['usen']) && // || should be &&; the || doesn't make sense here
strlen($_POST['usen']) >= 20 ) { // You had $usen['usen'] and an incorrectly placed )
$switch = substr($_POST['usen'], -9); // again, this should be $_POST['usen'], not $usen. The third parameter is unnecessary here.
$output_form = false;
} else {
$error_text .= "<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form = true;
}
The key points:
You're using the wrong boolean operator. !empty($x) || strlen($x) >= 20 doesn't make sense. It should be &&, not ||. If you have a non-empty value for $_POST['usen'], then !empty($_POST['usen']) is true. But because you had a || in your if conditional, this meant the if block always executed for non-empty values, never the else block. You only want the if to execute if the value is non-empty and at least 20 characters.
Your variable is $_POST['usen'], but your code referred to $usen['usen'] and $usen, which are incorrect.
You had strlen($usen['usen'] >= 20) where you should have strlen($_POST['usen']) >= 20. Both the variable name and the ) placement were incorrect.
To get the last 9 characters of $usen['usen'] use
$switch = substr($usen, -9);
if (!empty($_POST['usen']) ||
strlen($_POST['usen']) >= 20 ) { // changed condition
$switch = substr($usen, -9, 9); // returns last nine of sentence
$output_form=false;
} else {
$error_text .="<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form=true;
}
The if-condition has two issues in second part
You use $usen['usen'] but i think it schould be $_POST['usen'] (see also comment by #Ed Cottrell)
The closing bracker from method-call strlen has to be after the param
if (!empty($_POST['usen']) &&
strlen($_POST['usen'] )>= 20 ) { //condition change
$switch = substr($_POST['usen'] ,-9); // returns last nine of sentence
$output_form=false;
} else {
$error_text .="<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form=true;
}
To get last 9 charcters , you can use substr(string, -9);
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
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";
}