I have 3 stages to my if statement.
If is front page return true.
If is not front page but object is set and has certain value return true.
If not return false.
It worked as two seperate statement,
1) if is front page return true if not false
2) if object is set and has given value return true, objects is not set type return false.
When I try to put them as one statement I get true if front page but this rest doesn't return.
Code is below. Is their anything wrong with the statement? Thanks
<?php
$object = get_object();
if(is_front())
{
return 'true';
}
elseif (!(is_front() & !empty($object))) //is not front but object has been set check value
{
confirm_value();
}
else (!(is_front() & empty($object))) //if not front and object is not set
{
return 'false';
}
function confirm_value() {
$value = load($object); //load object
if($value->id($id)) //check value of id
{
return 'true';
}
else
{
return 'false';
}
}
?>
working code below
<?php
$object = get_object();
if(is_front())
{
return 'true';
}
elseif (!(is_front() && !empty($object))) //is not front but object has been set check value
{
return confirm_value();
}
else
{
return 'false';
}
function confirm_value() {
$value = load($object); //load object
if($value->id($id)) //check value of id
{
return 'true';
}
else
{
return 'false';
}
}
?>
Two problems I see:
1 - you are using a single & when you should be using &&.
2
confirm_value();
should be
return confirm_value();
I don't know the aim of code above but:
Use return confirm_value();
Else statement do not have condition. If you want check condition you should continue using elseif
Should using && instead of &. Because of & is bitwise operator. It will same result with && when all conditions are boolean. But when 1
& 2 == false
Related
I am trying to use ternary output to do 2 things on the latter case.
The issue I have is setting a text value to the variable in the latter case, after incrementing the error count.
I have tried a few things, here's two attempts, but these both fail on setting the $errors_log value.
Q. How can i set a variable value within an output of ternary.
$errors_v=0;
if (validate_username() == false ? null : $errors_v++ && $errors_log='username invalid');
if ($errors_v != 0) {
echo $errors_log;
}
function validate_username() {
return true;
}
$errors_v=0;
$errors_log[];
if (validate_username() == false ? null : $errors_v++ && $errors_log[]='username invalid');
if ($errors_v != 0) {
var_dump($errors_log);
}
function validate_username() {
return true;
}
I would do my ternary like below, and then check if $errors_log is not empty and if it's not, print out the errors.
$errors_log[] = validate_username() === false ? null : 'username invalid';
if (!empty($errors_log)) {
foreach($errors_log as $error) {
echo $error;
}
}
function validate_username() {
return true;
}
If it's needed to have a counter aswell, even though I really recommend you count on the $errors_log array instead, you could do something like this:
if (!validate_username()) {
$errors_log[] = 'username invalid';
$errors_v++;
}
You are mixing "longhand" and "shorthand" conditional syntax.
Your ambiguous function name coupled with its return value is confusing/unintuitive. I recommend renaming your function or reversing the boolean it returns.
Always endeavor to use DRY and DAMP coding practices.
The approach in the second half of your code looks better than the first.If you are going to generate an array of errors, don't bother with incrementing a counter, just count the array when you wish.
I don't see any need to fancy up your code with shorthand conditionals.
Code: (Demo)
function bad_username(){ // new meaningful function name
return true;
}
$errors_log=[]; // declare the variable as an array
if(bad_username()){
$errors_log[]='username invalid'; // push the value
}
if(sizeof($errors_log)){ // count elements in array, if 1 or more display them
var_export($errors_log);
}else{
echo "No Error";
}
Output:
array (
0 => 'username invalid',
)
You can't perform two operations in a ternary case. You could just check if $errors_log is empty and if it is increment $errors_v inside the if statement like this:
if (validate_username() == false ? null : $errors_log='username invalid');
if (!empty($errors_log)) {
$errors_v++;
echo $errors_log;
}
function validate_username() {
return true;
}
I am using 2 regex functions here and I wanna make another function which returns false when the 2 regex are both false and if not, then true.
The problem here is when I wanna use the 2 regex functions in the third one, I have to give them parameters, which is not necessary I think, because the third function will only return a simple true or false. I get an undefined variable whenever I give parameters to the 2 regex functions in the 3rd one.
I tried using global variables which works but since its a bad practice I am looking for a better solution.
Code:
function regex1($input)
{
$regex= "/^[A-Za-z0-9 ]*$/";
if (!preg_match($regex, $input))
{
return false;
}
else
{
return true;
}
}
function regex2($input)
{
$regex= "/^[A-Za-z0-9 ]*$/";
if (!preg_match($regex, $input))
{
return false;
}
else
{
return true;
}
}
function checkBoth()
{
if (regex1($input) === false || regex2($input) === false)
{
return false;
}
else
{
return true;
}
}
EDIT:
The checkBoth function I am using in my other file like this together with the other 2 regex functions:
if (!regex1($input))
{
// show error at the same time
}
if (!regex2($input))
{
// show error at the same time
}
if(checkBoth())
{
// success
}
function regex2($input,$secondVar=false)
{....
Later in code in place where you need just add:
if($secondVar !== false){
// do whatever...
}
If you can't user "false" you can just empty string '' or any other value that will not appear there.
Issue Resolved : Here is the solution :
function testCoreq()
{
$coreqTest = makeCoreq();
if(empty($coreqTest))
{
return array(true);
break;
}
else
{
foreach ($coreqTest as $ctest)
{
if($ctest['value'] == "true")
{
return array(true);
break;
}
else
{
return array(false,$ctest['coreqID']);
}
}
}
}
if(testCoreq()[0])
{
//do something
}
else
{
return testCoreq()[1]
}
I'm doing a school project and hit kind of a bump.
I created a function and i want it to either return "true" (boolean) or "false" (boolean) + a variable.
I searched the net quite a bit but wan't able to find a simple way to do this .
Is there any way to this this ? //Thanks
The function is working properly but when it is returning the variable - it is also assuming that the function is returning "true" when i want it to return false + the value like :
else
{
return $ctest['coreqID'];
return false;
}
Here is the code :
function testCoreq()
{
$coreqTest = makeCoreq();
if(empty($coreqTest))
{
return true;
break;
}
else
{
foreach ($coreqTest as $ctest)
{
if($ctest['value'] == "true")
{
return true;
break;
}
else
{
return $ctest['coreqID'];
}
}
}
}
I am using it like this:
if (testCoreq())
{
// do something
}
else
{
// return the variable
}
but even if the first statement is false , then it is returning the variable - it is assuming the function is true.
You can try to return -1 on true and other for false to decrease amount of returning values. Next option is to return array of values. The other option would be to pass reference variable in the function.
I have a function that returns TRUE or FALSE or "Test_operation", and I am looping it to do some things. As you can see the value of $comment_reply is Test_operation.
$comment_reply = $this->Profunction->insert_comments();
echo $comment_reply; // returns Test_operation
if ($comment_reply==TRUE)
{
echo json_encode('Success');
}
elseif($comment_reply==FALSE)
{
echo json_encode('Failed');
}
elseif($comment_reply =="test_operation")
{
echo json_encode('This Action Cannot be done!');
}
But still
if ($comment_reply==TRUE)
{
echo json_encode('Success');
}
This portion getting executed. Why does it happen?
In that function I am returning like this:
return TRUE; // if all success
return FALSE; // if there is some problems
return "Test_operation"; //No insertion need to be done,may be for preview purpose.
SOLVED : I changed bool values to string.
So it will be
return 'TRUE'; // if all success
return 'FALSE'; // if there is some problems
return "Test_operation"; //No insertion need to be done,may be for preview purpose.
Not sure it's your issue, but if you want to enforce equality by type and value, use the === operator.
You can check this out in more detail on the comparison operator page.
Happy coding
Try using === instead of ==
I am looking for the correct way to handle a return statement with a bool/string. For example I do all my checking inside the function and return true if it all passes. However if something went wrong I would like to return a string of what went wrong rather than just return false; with a general string. Does php assume false if a var is set to anything besides true? What is the correct way to handle this? Here's an example of what I'm doing
<?php
$a = 2;
$result = CheckVar($a);
if ($result)
{
echo 'Correct!';
}
else
{
echo $result;
}
function CheckVar($var)
{
if ($var == 1)
{
return true;
}
else
{
return 'This is not the correct answer. You supplied '.$var;
}
}
?>
It seems this method works, however is this good programming etiquette? Or is there another way I should be doing this? Thank you for your time.
Does php assume false if a var is set to anything besides true?
Not at all. PHP will return whatever the variable was set to. And actually since you have a non-empty string, that's a "truthy" value (ie: true in a boolean context). Since you used if ($result) as your check and you return a "truthy" value, the condition is always true. You need to change that check to:
if ($result === true) {
...
What is the correct way to handle this?
I think it's a good enough way to handle it. An alternative would be to pass an error string variable by reference, and have the fail part of your code fill that, eg:
function check($var, &$error) {
if ($var == 1) {
return true;
} else {
$error = 'This is not the correct answer. You supplied ' . $var;
return false;
}
}
Some native PHP functions behave like this (eg: exec().) Yet another alternative is to return an array with the errors, like Jared suggested. I personally use this option when I expect multiple errors (eg: a form validation routine):
function check_stuff($stuff) {
$errors = array();
if (!$condition1) {
$errors[] = 'Condition 1 failed';
}
if (!$condition2) {
$errors[] = 'Condition 2 failed';
}
return $errors;
}
Now you can also take advantage of the fact that empty arrays are falsy:
$errors = check_stuff($your_stuff);
if (!$errors) {
echo 'No errors!';
} else {
print_r($errors);
}
You can use === to check if the returned value is boolean true. === checks the type as well the value.
if ($result === true)
{
echo 'Correct!';
}
else
{
echo $result;
}
I came up against this recently, my function would either return an error message as a string or return true like this:
function check_something(){
if(condition){
return 'error message';
}
// if we got this far all is good!
return true;
}
I would call it and check the outcome like this:
$var = check_something();
if($var !== true){
// $var is not boolean true, so it must be a string
echo $var;
}
This checks that the outcome of the function is not just a truthy string, but is explicitly a boolean true
This could be useful to someone returning true or returning false as a string.
if (is_bool($result))
{
echo 'Result is a true bool';
}
else
{
echo $result.'returning a string';
}