How to shorten this line of code? - php

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:'');

Related

PHP ternary operators

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).

php function return a Boolean and use it on condition

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

Using $_Request inside function PHP

1)
I have this:
function ObtainRequest($Field, $Method) {
$Returned = "";
if ($Method == "POST")
$Returned = $_POST[$Field];
else if ($Method == "GET")
$Returned = $_GET[$Field];
else
$Returned = $_REQUEST[$Field];
return $Returned;
}
Now, using the function:
if (isset(ObtainRequest("OneField","POST"))) {
DoSomething();
} else if (!isset(ObtainRequest("OneField","POST"))) {
DoOtherthing();
}
But my script isn't running (SHOWING PLANK PAGE)...
What's my mistake?
2)
The $_REQUEST is lost inside of function?
This code works!!:
if (isset($_REQUEST["OneField"])) {
DoSomething();
}
This code doesn't work!!:
if (isset(ObtainRequest("OneField","REQUEST"))) {
DoSomething();
}
This code doesn't work!!:
if (empty(ObtainRequest("OneField","REQUEST"))) {
DoSomething();
}
3)
Is it applicable to Session too?
Your mistake is here:
$Method == "Post"
But you passing uppercased POST:
ObtainRequest("OneField","POST")
Fix with strtoupper():
function ObtainRequest($Field, $Method) {
$Returned = "";
$Method = strtoupper($Method);
if ($Method == "POST")
$Returned = isset($_POST[$Field]) ? $_POST[$Field] : false;
else if ($Method == "GET")
$Returned = isset($_GET[$Field]) ? $_GET[$Field] : false;
else
$Returned = isset($_REQUEST[$Field]) ? $_REQUEST[$Field] : false;
return $Returned;
}
Also, this function might be shortened with switch construction:
function ObtainRequest($Field, $Method) {
switch(strtoupper($Method)){
case "POST": return isset($_POST[$Field]) ? $_POST[$Field] : false;
case "GET": return isset($_GET[$Field]) ? $_GET[$Field] : false;
default: return isset($_REQUEST[$Field]) ? $_REQUEST[$Field] : false;
}
}
Second problem is that isset() might be used with variables, but not with function results. Use boolean check instead:
if (ObtainRequest("OneField","POST") !== false) {
DoSomething();
} else if (ObtainRequest("OneField","POST") === false) {
DoOtherthing();
}
Is it applicable to Session too?
Well, if you interested in my opinion: I would not mix $_SESSION in such function with $_POST, $_GET and $_REQUEST, because $_SESSIONs meaning is different. Also, it exists differently, not like them.
However something like this function might be realized for $_SESSION itself.
The first problem which I can see that you are using post instead of POST...
yes you can do this with sessions too, but codes need to be modified a bit..

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");

Categories