PHP ternary operators - php

I have written a ternary function in PHP and it seems to work, although I am not sure if it is correct, can someone take a look and tell me if it is right?
I have added the ternary and the if of what should be happening.
//Foreach Loop
foreach ($post as $item) {
//If of what should occur
if ($passed == true) {
if (is_numeric($item)) {
if ($item > 0) {
$passed = true;
}
else {
$passed = false;
}
}
else {
if ($item != "") {
$passed = true;
}
else {
$passed = false;
}
}
//Ternary operator.
$passed = (is_numeric($item) ? ($item > 0 ? true : false) : ($item != "" ? true : false));
}
else {
return $passed;
}
}

please have a look on corrected code
$passed = (is_numeric($item))?($item>0?true:false):($item !="" ? true:false);

Honestly I do not really understand why you do not use a
if (!empty($item)) {
$passed = true;
} else {
return false;
}
In any case, ternaries are less readable than if /elseif / else, they are also slower (note that it is not an universal truth but a more general use case thing http://fabien.potencier.org/the-php-ternary-operator-fast-or-not.html).
I would recommend, if you really need all these if and elses to keep them rather than using ternaries (for readability's purpose).

Related

PHP Return true in foreach

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;
}

How to shorten this line of code?

i want to ask, how can i shorten this code?
I've tried with ifelse but i dont get it..
I have this
if (empty($data['current_password'])) {
return false;
}
if (empty($data['new_password'])) {
return false;
}
if ($data['new_password'] !== $data['new_password_again']) {
return false;
}
Tried
if () {
} elseif (empty($data['current_password'])) {
} elseif ($data['new_password'] !== $data['new_password_again']) {
}
But doesnt work, please help
thank you very much
You can do like this
if (empty($data['current_password']) || empty($data['new_password']) || $data['new_password'] !== $data['new_password_again'])
{
return false;
}
If you like magical things, try this
switch (true) {
case (empty($data['current_password'])):
case (empty($data['new_password'])):
case ($data['new_password'] !== $data['new_password_again']):
return false;
}
This ?
return (empty($data['current_password']) || empty($data['new_password']) || $data['new_password'] !== $data['new_password_again']) ? false : '';
try below one,
return(empty($data['current_password'])||empty($data['new_password'])||$data['new_password'] !== $data['new_password_again']?FALSE:'');

Set and validate return value in IF in PHP

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;
}

Multiple conditional statement

What's the best way to write this in PHP, so I know which condition fails and is easy to maintain? Without resorting to multiple if else statements...
if ((!$titleBlockPresent || !$leadBlock || ($allDoubleBlockCount !=2 || $allDoubleBlockCount!=1) ||$countFirstSmallShowBlocks !=2 ||$countSecondSmallShowBlocks !=2 ) && !$contentNotAvailableMessage)
{
$this->fail("Block missing in the horizontal list of blocks on the non live carousel");
}
try this
$shouldFail = FALSE;
switch(TRUE){
case !titleBlockPresent:
echo "No title block present<br/>";
$shouldFail = TRUE;
case !$leadBlock:
echo "No lead block<br/>";
// the rest of the code
}
If you move that check into the function, it'll be clear for you and anyone else looking at your code, and very easy to maintain, for example:
function tester($var1, $var2, $var3)
{
if (!$var1)
{
$this->fail("error1");
return FALSE;
}
if (!$var2)
{
$this->fail("error2");
return FALSE;
}
if (!$var3)
{
$this->fail("error3");
return FALSE;
}
return TRUE;
}
You could also add a comment to each if that needs further clarification.
I just come up with this, but noticed that it is very similar to GeoPhoenix's answer, just the other way around, may be worth checking this out, as well:
$bFail = false;
if(!$bFail && $contentNotAvailableMessage) $bFail = true;
if(!$bFail && !$titleBlockPresent ) $bFail = true;
if(!$bFail && !$leadBlock ) $bFail = true;
if(!$bFail && $allDoubleBlockCount != 2) $bFail = true;
if(!$bFail && $allDoubleBlockCount != 1) $bFail = true;
if(!$bFail && $countFirstSmallShowBlocks != 2) $bFail = true;
if(!$bFail && $countSecondSmallShowBlocks != 2) $bFail = true;
if($bFail) $this->fail("Block missing in the horizontal list of blocks on the non live carousel");

What would you change in my code for best practices/maintenance?

I've got a small snippet of code below and I was curious what types of things you would change with regards to best practices/code maintainablity and so on.
function _setAccountStatus($Username, $AccountStatus)
{
if ($Username == '' || ($AccountStatus != 'Active' || $AccountStatus != 'Banned' || $AccountStatus != 'Suspended')) {
// TODO: throw error here.
}
$c1 = new Criteria();
$c1->add(UsersPeer::USERNAME,$Username);
$rs = UsersPeer::doSelect($c1);
if (count($rs) > 0) {
$UserRow = array_pop($rs);
$UserRow->setAccountStatus($AccountStatus);
try {
$UserRow->save();
} catch ( PropelException $e ) {
return false;
}
return true;
}
return false;
}
I would use the empty() instead of $Username == '' in your if statement. I haven't used propel before, but I would prefer to have this method be on my User object itself with the fetching and saving of the user object performed by a seperate object. Pseudo code would be something like this.
$user = userManager->getUser($username);
$user->setAccountStatus($accountStatus);
$userManager->saveUser($user);
An else clause before the last return false would be prefererred, just to make the code more readable.

Categories