I've some problems with handling Boolean values in PHP. It is a validation script before storing data into database. I wrote a global validator that will validate and return a Boolean value whether the validation was successful .
Here is my code.
//VALIDATE
$isValid = true;
foreach($team as $key=>$val) {
if(!is_array($val)){
$isValid = $isValid && validate($val, $key);
}
}
for($it=0;$it<count($team['members']);$it++){
foreach($team['members'][$it] as $key=>$val) {
$isValid = $isValid && validate($val, $key);
}
}
if(!$isValid) { // EDITED: if(!isValid)
echo "validation error";
exit(1);
}
//END OF VALIDATE
The validate function is working properly but sometimes I end up getting $isValid = true or the other way, when I try with some test cases.
Hmm.. What am I doing wrong here ?
Please check, if this form does the trick:
if( false === $isValid) {
echo "validation error";
exit(1);
}
Note, that ( ! $isValid ) or (false == $isValid ) in some cases return results, which are at first look wrong. See for example the hint in the strpos() documentation.
In fact, the results are fine, since operations line ! or == try to cast operands in a 'useful' way.
That said, it's always better to user the === operator, since it checks values and types of operands. Please see operator overview.
if(!isValid) { falls back to if (!"isValid"), if there is no constant isValid. You probably meant if (!$isValid) {.
if(!isValid) {
isValid has no dolar, (you need to give variables in PHP some cash) so:
if(!$isValid) {
Source : http://bit.ly/1hxDmVR
Here is sample code for working with logical operators in PHP. Hope it will helpful:
<html>
<head>
<title>Logical</title>
</head>
<body>
<?php
$a=10;
$b=20;
if($a>$b)
{
echo " A is Greater";
}
elseif($a<$b)
{
echo " A is lesser";
}
else
{
echo "A and B are equal";
}
?>
<?php
$c=30;
$d=40;
//if(($a<$c)AND($b<$d))
if(($a<$c)&&($b<$d))
{
echo "A and B are larger";
}
if(isset($d))
$d=100;
echo $d;
unset($d);
?>
<?php
$var1=2;
switch($var1)
{
case 1:echo "var1 is 1";
break;
case 2:echo "var1 is 2";
break;
case 3:echo "var1 is 3";
break;
default:echo "var1 is unknown";
}
?>
</body>
</html>
I think the problem is that your $isValid variable can be changed many times in the loops and by the end of your code simply applies to the last value in your final loop.
You should set it to true initially and then only set it to false IF your validity check fails - not simply assign its value based on every single validity check.
Related
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';
}
I have created two links where I would like the page contents to change. The problem is the URL changes but not the page content.
<h3>Filter Results</h3>
<p><a href="index.php?filter='Action'>Action</a></p>
<p>Comedy</p>
if (isset($_GET['filter']) == 'Action') {
echo 'Action';
}
else if (isset($_GET['filter']) =='Comedy') {
echo 'Comedy';
}
It always outputs the first link information "Action".
Your links are faulty:
<p>Action</p>
<p>Comedy</p>
<!-- ^ ^ No single quotes (' ') -->
Yogesh Suthar pointed it out first
Also, isset() will return a boolean (true or false; based on whether or not the variable is set). You're comparing a boolean to a string, a string will always be converted into TRUE (unless the string is "false" or similar), so basically, if the variable is set, the first condition will always match.
You want
if (isset($_GET["filter"]) && $_GET["filter"] === "Action")
Note the use of ===, this will make sure that the variable is exactly what you think it is, and not some sort of other type variable.
Few more points (Shamelessly stolen taken from other answers)
If there are multiple possible filters, check for the variable existance once, and use a switch/case block to determine which of them it is:
if(isset($_GET['filter'])) {
switch($_GET['filter']) {
case 'Action':
echo 'Action';
break;
case 'Comedy':
echo 'Comedy';
break;
}
}
The function isset will only check if the variable is existing! It will not return its value! Try this instead:
<h3>Filter Results</h3>
<p>Action</p>
<p>Comedy</p>
if(isset($_GET['filter']) && $_GET['filter'] == 'Action'){
echo 'Action';
}
else if(isset($_GET['filter']) && $_GET['filter'] == 'Comedy') {
echo 'Comedy';
}
Also, using switch might make things easier in the future:
<h3>Filter Results</h3>
<p>Action</p>
<p>Comedy</p>
if(isset($_GET['filter'])) {
switch($_GET['filter']) {
case 'Action':
echo 'Action';
break;
case 'Comedy':
echo 'Comedy';
break;
}
}
As #MadaraUchiha said about isset and,
if(isset($_GET['filter']) == 'Action')
should be
if(isset($_GET['filter']) && $_GET['filter'] == 'Action')
Also
<a href="index.php?filter='Action'>Action</a>
^ ^ ^ // here you started " but not ended and remove the single quotes around Action
should be
Action
Make sure that you insert an opening and a closing php tag: <?php and ?> To simplify it a bit you could just echo the value you get via $_GET
<h3>Filter Results</h3>
<p><a href="index.php?filter='Action'>Action</a></p>
<p><a href="index.php?filter='Comedy'>Comedy</a></p>
<?php
if(isset($_GET['filter'])){
echo $_GET['filter'];
}
?>
The function isset will return true or false (it checks whether the variable is set or not). Change your code:
if(isset($_GET['filter']) && $_GET['filter'] == 'Action') {
Your if condition is not correct do it:
if(isset($_GET['filter']) && $_GET['filter'] == 'Action'){
echo 'Action';
}
Similarly with else if:
else if(isset($_GET['filter']) && $_GET['filter'] =='Comedy') {
As you are comparing the isset($_GET['filter']) with the value although isset returns true of false so you need to compare the value of $_GET['filter'].
you dont have to use isset() and then compare.
$filter = $_GET['filter'];
if(isset($filter)){
if($filter == 'Action'){
echo 'Action';
}else if($filter == 'Comedy'){
echo 'Comedy';
}
}
isset returns true and since 'Action' is not null, it evaluates to true.
if ((isset($_GET['filter'])) && ($_GET['filter'] == 'Action')) {
// ...
} else if ((isset($_GET['filter'])) && ($_GET['filter'] == 'Comedy')) {
// ...
}
BTW such code would sooner or later become a nightmare to maintain.
You could instead, for example
function preventDirectoryTraversal($requestParam) {
return preg_replace("/\//", "", $requestParam);
}
// ...
if (isset($_GET['filter'])) {
$filterName = preventDirectoryTraversal($_GET['filter']);
include(FILTERS_DIR . "/" . $filterName . ".php");
}
or something alike. Of course this can be further improved, but I hope you get the point.
Wrong use of isset, check documentation, return a boolean.
if (isset($_GET['filter']))
{
switch ($_GET['filter'])
{
case 'Action':
//TODO
break;
case 'Comedy':
// TODO
break;
default:
// TODO
break;
}
}
//isset will always return true or false
if(isset($_GET['filter'])){
if($_GET['filter']=='Action')
{
echo 'Action';
}elseif($_GET['filter']=='Comedy'){
echo 'Comedy';
}
}
I wrote this:
$a[] = "guy";
$b[] = "g";
function login($a1, $b1)
{
if( user($a1) == true and pass1($b1) == true)
{
login2($a1, $b1);
}
else
{
echo "error!!!!";
}
}
function login2($a1, $b1)
{
if (array_search($_REQUEST["user"],$a1) == array_search($_REQUEST["pass"],$b1))
{
echo "you are logged in";
}
else
{
echo "erorr";
}
}
function user($user1)
{
if(in_array($_REQUEST["user"],$user1))
{
echo "gooooooood?";
}
}
function pass1($pas)
{
if(in_array($_REQUEST["pass"],$pas))
{
echo "goooooooood!!!!!!!!";
}
else
{
echo "bad";
}
}
login($a, $b);
and I know that pass() and user() are true because I changed their positions on the function login() and every time I did this the first argument was returned as true and it didn't check the second one. Does anyone know why this happens?
user and pass1 functions should return true or false, not echo out.
Your user and pass1 functions are not returning an explicit value, so they are implicitly returning the NULL value. As described on this page in the PHP manual the NULL type is converted to false when a boolean is expected. So both your user and pass1 functions return false every time.
The && and and logical operators in PHP use short-circuiting for efficiency (see the first code example on this page of the PHP manual) so in any and statement whose first operand evaluates to false it can never be possible for the whole and statement to evaluate to true, so the second operand (in the case of your code above, the second operand is the call to pass1($b1)) is never evaluated because it would be a waste of time to do so.
Which means you're seeing the user function being called, but never the pass1 function.
Try using this instead:
$a[] = "guy";
$b[] = "g";
function login($a1, $b1)
{
if( user($a1) == true && pass1($b1) == true)
login2($a1, $b1);
else
echo "error!!!!";
}
function login2($a1, $b1)
{
if (array_search($_REQUEST["user"],$a1) == array_search($_REQUEST["pass"],$b1))
echo "you are logged in";
else
echo "erorr";
}
function user($user1)
{
if(in_array($_REQUEST["user"],$user1))
echo "gooooooood?";
}
function pass1($pas)
{
if(in_array($_REQUEST["pass"],$pas))
echo"goooooooood!!!!!!!!";
else
echo "bad";
}
login($a, $b);
I know there must be a nicer way to do this, but whenever I search "&&" i don't get good enough results...
<?php
if (empty($row[ContactName]) && empty($row[ContactEmail]) && empty($row[ContactPhone]) && empty($row[Website])){
echo "Not Provided";
}
else{
...do stuff...
}
?>
Thanks!
What is wrong with the original code?
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
Looks like fine code to me...
<?php
$i=1;
$ar=array('ContactName','ContactEmail','ContactPhone','Website')
foreach($ar as $a)
if (empty($row[$a]))
{
$i=0;
break; //to make code fast
}
if($i) //do stuff
else echo 'not provided';
?>
or if you really want to make your code extra small then change your column name in database
From To
ContactName Col1
ContactEmail Col2
ContactPhone Col3
Website Col4
and then do
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
else echo 'Not Provided';
?>
However it is not good to rename column as it will make your db somewhat less understandable.
As php functions have a lot of inconsistency, It's always a good idea using a library to make it more consistent.
put this function in that library:
function empty()
{
foreach(func_get_args() as $arg) if (empty($arg)) return false;
return true;
}
usage:
if (empty($row[ContactName], $row[ContactEmail], $row[ContactPhone], $row[Website])) {
echo "Not Provided";
}
you could make it as short as this if compactness was more important than readability :)
$required = array('ContactName', 'ContactEmail', 'ContactPhone', 'Website');
$ra = array_filter(array_intersect_key($row,array_flip($required)));
if(empty($ra)){
echo "Not Provided";
}
else{
//....
}
you can't put array_filter inside empty() or you get "Fatal error: Can't use function return value in write context"
1) array flip is turning your $required values into keys
2) array_intersect_key throws away any $row keys not found in $required
3) array_filter throws away any empty values
leaving you with a zero length array, which is empty. No need to worry about array lengths or loops
<?php
$flag = 1;
if (empty($row[ContactName])){
$flag = 0;
}
if (empty($row[ContactEmail])){
$flag = 0;
}
if (empty($row[ContactPhone])){
$flag = 0;
}
if (empty($row[Website])){
$flag = 0;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
?>
OR
$flag = 1;
$i=0;
$mustarray = array('ContactName','ContactName','ContactName','ContactName'); //or any number of fields that you want as mandatory
foreach($yourresult as $row){
if(empty($row[$mustarray [$i]])){
$flag = 0;
}
$i++;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
Do not play with making arrays and stuff just to make code look nicer.
As Tommy pointed
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
this code is nice, just need proper formatting like he pointed.
Making arrays and then launching loop will decrease performance
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
?>
this might look small, nice and "pro", but has more operations to give same results as a simple if instruction.
Not saying that it cant be done faster, i don't know php well, just remember about code executing speed.
I have submitted some code to the redirected url and now trying to use this to echo some information out but can't figure out where I am going wrong.
I have the following code:
<?php $login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt) == '1'{
return 'failed';
}
?>
all I want to do is if the url has $login_attempt=1 I want to return the message 'failed' to the page.
There is no point of escaping anything if it doesn't enter anywhere important (like a database).
<?php
if ($_GET['login_attempt'] == '1') {
echo 'failed';
}
?>
Also, you have a problem in your if statement, that's corrected in the code above. Be sure to include all of the condition inside of parenthesis, and not just one side of the equality check.
Also, if you wish to display something on the screen, you should echo it, not return.
how about:
if ($login_attempt == '1'){
echo 'failed';
}
Try this one. Your error in $login_attempt == '1':
<?php $login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt == '1'){
echo 'failed';
return false;
}
?>
As others already mentioned you have several problems but the syntax error comes from this:
if ($login_attempt) == '1'{
it should be
if ($login_attempt == '1') {
Dont u think if ($login_attempt) == '1' should be something like this ($login_attempt == '1') Sorry...many others also suggested this :P
At the first, I must tell you that you have a mistake in your IF condition. You typed == outside of ().
In addition, you have to be aware of status of setting your variable through your URL. Check the code below. In this code, I made a function to check the status. Default status is true, and we will check it just for a negative condition. I hope it could be useful for you:
<?php
function check() {
if (isset($_GET['login_attempt'])) {
$login_attempt = mysql_real_escape_string($_GET['login_attempt']);
if ($login_attempt == '1') {
return false;
} else {
return true;
}
} else {
return true;
}
}
if (!check()) echo('Error Message');
?>