I want to check if the user is using the default settings. In the example below, I'm trying to check if all "foreached" items return true. If a single foreached item doesn't return true, return false on the whole function.
private function is_using_default_settings() {
// returns a huge array with settings
$merged_preset = $this->options_merged();
foreach($merged_preset as $preset) {
if($preset[5] == 1) {
$section = 'general';
} elseif($preset[5] == 2) {
$section = 'advanced';
} elseif($preset[5] == 3) {
$section = 'technical';
}
$option = get_option($section);
if($preset[3] == $option[$preset[0]] && !is_null($preset[1])) {
return true;
}
}
return false;
}
I've been brainstorming for the past few days to get this sorted on my own, but sadly cannot get it to work. What is the best approach to this?
you can check when is false and block the full foreach then return value, if all is true return value true
try this:
private function is_using_default_settings() {
$returnValue = true;
$merged_preset = $this->options_merged();
foreach($merged_preset as $preset) {
if($preset[5] == 1) {
$section = 'general';
} elseif($preset[5] == 2) {
$section = 'advanced';
} elseif($preset[5] == 3) {
$section = 'technical';
}
$option = get_option($section);
if($preset[3] != $option[$preset[0]] || is_null($preset[1])) {
$returnValue = false;
break;
}
}
return $returnValue;
}
You should return false when any check fails in the foreach, otherwise return true.
function check()
{
foreach($arr as $v)
{
//check fails
if(fail of the check)
return false;
}
return true;
}
Related
In the following code snippet while loop does not stops while condition become false.
public function isCircularDependancy($taskId, $newParentId){
global $pdoHandlerObject;
$task = $this->getTaskById($taskId);
if($newParentId == 0){ // This is root task there is no parent
return false;
}
if($task->parent_id == $newParentId){ // Parent is not changed
return false;
}
$currentParentId = $newParentId;
while($currentParentId != 0){
if($currentParentId == $task->id){
return true;
}
$currentParent = $this->getTaskById($currentParentId);
$currentPatentId = $currentParent->parent_id;
}
return false;
}
I have a function, as shown in the code below, that should return true if the code is executed correctly. Nothing new.
The problem is that the function calls other functions, each returns true or false.
I'm trying to figure out how to construct the logic to validate the output of the function checking the code of the function itself, and the returns of the other functions. The other functions might be called or not, depending on the $this->conf['functionName'] parameter, which is also a boolean.
public function execute() {
$return = false;
if ($this->conf['functionOne']) {
$this->functionOne();
}
if ($this->conf['functionTwo']) {
$this->functionTwo();
}
if ($this->conf['functionThree']) {
$this->functionThree();
}
return $return;
}
I would do this
public function execute() {
$function_list = ['functionOne', 'functionTwo', 'functionThree'];
$return = true;
foreach ($function_list as $function) {
if ($this->conf[$function]) {
if (!$this->{$function}() && $return) {
$return = false;
}
}
}
return $return;
}
It's not quite clear but I think you mean something like this...
public function execute() {
$res1 = $res2 = $res3 = true;
if($this->conf['functionOne']){
$res1 = $this->functionOne();
}
if($this->conf['functionTwo']){
$res2 = $this->functionTwo();
}
if($this->conf['functionThree']){
$res3 = $this->functionThree();
}
return ($res1 && $res2 && $res3);
}
Do you mean this:
public function execute() {
$return = false;
if($this->conf['functionOne']){
$return = $this->functionOne();
}
if($this->conf['functionTwo']){
$return = $this->functionTwo();
}
if($this->conf['functionThree']){
$return = $this->functionThree();
}
return $return;
}
Is this works ?
public function execute() {
$f1 = $f2 = $f3 = false ;
if($this->conf['functionOne']){
$f1 = $this->functionOne();
}
if($this->conf['functionTwo']){
$f2 = $this->functionTwo();
}
if($this->conf['functionThree']){
$f3 = $this->functionThree();
}
if($f1=== true && $f2===true && $f3===true)
return true;
else
return false ;
}
im not sure on how i am going to explain this correctly.
I wanted a function to validate a string which i figured correctly.
But i want the function to return a boolean value.
And outside a function i need to make a condition that if the function returned false, or true that will do something. Here's my code.
i am not sure if this is correct.
<?php
$string1 = 'hi';
function validatestring($myString, $str2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
}
}
else {
return false;
}
}
if(validatestring == FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
EDIT : Now what if there are more than 1 condition inside the function?
<?php
$string1 = 'hi';
function validatestring($myString, $myString2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
return true;
}
else {
retun false;
}
}
else {
return false;
}
}
if(validatestring($myString, $myString2) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Functions need brackets and parameter. You dont have any of them.
This would be correct:
if(validatestring($myString) === false) {
//put some codes here
}
An easier and more elegant method would be this:
if(!validatestring($myString)) {
//put some codes here
}
<?php
$string1 = 'hi';
function validatestring($myString) {
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring($string1) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Sidenote, since empty() already returns false ,you could simplify by doing:
function validateString($string){
return !empty($string);
}
if(validateString($myString){
// ok
}
else {
// not ok
}
To make a check and test later:
$check = validateString($myString);
if($check){ }
There's no need to check == false or === false, the function already returns a boolean, it would be redundant.
store $string1 to $myString in the function
myString=string1
<?php
$string1 = 'hi';
function validatestring($myString) {
myString=string1;
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring() === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
Could I do this in PHP?
if ($Var = $this->test1() == true) {
var_dump($Var);
}
public function test1() {
return true;
}
It echoes true, but I'm not sure if this is the correct way to check such return values.
Yes you can, but write:
if (($var = $this->test1()) === true) {
var_dump($var);
}
To be safe and to alert the reader there is something going on.
I wouldn't advise you to do this though, but in some cases this is acceptable; such as a complex if-else tree where lazy execution is desirable.
if (($result = slow_process()) !== false) {
return $result;
} else if (($result = slow_process1()) !== false) {
return $result;
} else if (($result = slow_process2()) !== false) {
return $result;
} else if (($result = slow_process3()) !== false) {
return $result;
}
This is overly simplified, but these situations do occur.
You can but there is 2 things you should be aware of :
When you do something like :
if ($Var = $this->test1() == true) {
The operators are confusing :
do you want to do $this->test1() == true and store result $var
do you want to do $var = $this->test1() and compare it with true
In your case, $this->test1() returns true so it does not matter. But if we change your code a bit :
if ($Var = $this->test1() == 5) {
var_dump($Var);
}
public function test1() {
return 3;
}
Someone who read your code will not understand if you want to store $this->test1() in $Var (so, make 3 in var) or if you want to put result of comparison $this->test1 == 5 in $Var (false).
What remains in $Var at the end may be a very good question at the PHP 5.3 Certification but not in a useful case.
To avoid mistakes, uses parenthesis :
if (($var = $this->test1()) == true) {
You should take care of types :
I give you an example of what could return something castable to true :
function test1() { return true; }
function test2() { return 3; }
function test3() { return 3.42; }
function test4() { return "x"; }
function test5() { return array('x'); } // array() == true returns false
function test6() { return new stdClass(); }
echo test1() == true;
echo test2() == true;
echo test3() == true;
echo test4() == true;
echo test5() == true;
echo test6() == true;
// outputs 111111 (1 = true)
To avoid mistakes, you should use === operator. Your final piece of code becomes :
if (($var = $this->test1()) === true) {
The == true part is unnecessary. What you have is valid syntax, but some find it confusing. You can always do:
$Var = $this->test1();
if ($Var) { ...
Just decide on the standard with your development team.
You can also do:
if ($Var = $this->test1()) {
var_dump($Var);
}
public function test1() {
return true;
}
I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}