Converting a PHP if/else statement to use ternary format - php

I want to convert this if/else statement to ternary format:
function session_active()
{
if ($_SESSION['p_logged_in']) {
return true;
}
else {
return false;
};
}
I tried:
function session_active()
{
($_SESSION['p_logged_in'] ? true : false);
}
but it always returns false.
I am looking at the examples at http://davidwalsh.name/php-ternary-examples and this seems correct as far as I can see from the examples. Why does it always return false?

You may try to simple return the $_SESSION['p_logged_in'] value :-
function session_active()
{
return (bool)$_SESSION['p_logged_in'];
}

php isnt ruby, you have to return that value from the ternary.
to elaborate in more detail...
function session_active()
{
return ($_SESSION['p_logged_in'] ? true : false);
}

Try this:
function session_active() {
return (isset($_SESSION['p_logged_in'])) ? true : false;
}

to correct your logic add return in front of your statment
to simplify it do: return (bool)$_SESSION['p_logged_in'];

There is a difference between $_SESSION['p_logged_in'] === true vs $_SESSION['p_logged_in'] != null, by returning $_SESSION['p_logged_in'] could in affect be more than what it is testing for.

Related

Why can't I use an "if" statement to return true/false in a PHP function?

Why does it not work to use an if statement to determine if a function should return true or false? True works, but false doesn't.
Here is my code:
function test($var){
if($var == "string"){
return true;
}else{
return false;
}
}
Doing:
echo test("string"); returns true as it should, but using echo test("hello"); should return false, but returns nothing, why?
What should be used instead for returning true/false with criteria?
Well it does work on my side
Using :
function test($var){
if($var == "string"){
return true;
}else{
return false;
}
}
echo "string:";
var_dump(test("string"));
echo "hello:";
var_dump(test("hello"));
cause the output
string:bool(true)
hello:bool(false)
When you want see the output of something always use var_dump() as false produces no output when echoed directly.
var_dump(test("hello"));
Echoing false deceptively produces no output. Try var_dump instead; it will show you the true value.
bool(false)
I see no reason why your code doesn't work, but this would be shorter:
function test($var) {
return ($var == "string");
}
Your code is dangerous - this means probably wrong.
Use === instead of ==
if ($var === "string") { ...
Read the doc ;)

function return code block query

Quick question to do with php functions, it may sound silly to some of you but I dont want to get in to bad habits. Is there anything wrong with doing the following?
function do_something($val)
{
$a = 1;
if ($val==$a)
{
return true;
}
return false;
}
Instead of;
function do_something($val)
{
$a = 1;
if ($val==$a)
{
return true;
}
else
{
return false;
}
}
Sorry guys I think my example isn't great. Basically the function could insert data into a database or send an email etc. With these functions I may only need to now whether it was successful or not by returning true or false. I wanted to know whether its suitable that I can use the shorter method instead of the if-else block.
I hope that makes it clearer.
Not really. Both works the same. However, it would be much cleaner to write it like this:
function do_something($val)
{
$a = 1;
return ($val==$a) ? true : false;
}
That's totally cool, because when returning a value, the function is left and it doesn't matter what follows.
But you could shorten this with
function do_something($val)
{
$a = 1;
return $val == $a; // this condition will be evaluated to true/false
}
The shortest way to do it:
function do_something($val)
{
return ($val==1) ;
}
No, that is perfectly fine, and in fact advised in multiple cases. :)

String value equals true

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 ==

Cant figure out operators in php statement

I need to edit a function, but I cant figure out what the ? and the : false mean in the return statement. I think the : is an OR but the ? I dont know.
public function hasPermission($name)
{
return $this->getVjGuardADUser() ? $this->getVjGuardADUser()->hasPermission($name) : false;
}
Anyone that can clear this up for me?
It is PHP's Ternary Operator. It's like a shorthand for if/else expressions.
Your expanded code could look like so:
public function hasPermission($name)
{
if ($this->getVjGuardADUser()) {
return $this->getVjGuardADUser()->hasPermission($name)
} else {
return false;
}
}
Some sample-code from php.net:
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
It's the ternary operator, a simple oneliner if then construct.
This is the ternary operator. It's documented here.
It's a short form for:
public function hasPermission($name) {
if ($this->getVjGuardADUser()) {
return $this->getVjGuardADUser()->hasPermission($name)
} else {}
return false;
}
}
I recommend the more verbose style for conditional statements for better readability, though.
It's called the ternary operator.
variable = predicate ? /* predicate is true */ : /* predicate is false */;
In your code, it's a shorthand form of the following:
if($this->getVjGuardADUser())
return $this->getVjGuardADUser()->hasPermission($name);
else
return false;
It's a ternaire expression.
You can replace this by:
if ($this->getVjGuardADUser())
return $this->getVjGuardADUser()->hasPermission($name);
return false;
It's a ternaire operator. Read more about it here:
http://www.lizjamieson.co.uk/2007/08/20/short-if-statement-in-php/
http://www.scottklarr.com/topic/76/ternary-php-short-hand-ifelse-statement/

How to convert the ASP code snippet to PHP?

function isChongHao(ary,i,j)
if ary(i-1,j)<>0 or ary(i+1,j) then
isChongHao=true
exit function
end if
isChongHao=false
end function
function isChongHao($ary, $i, $j) {
if($ary[$i-1][$j] != 0 || $ary[$i+1][$j]) {
return true;
}
return false;
}
--I suppose $ary contains a name of a function.--
Ooops, strike that: Joel thanks, I totally missed the fact that it was vbscript!!! O.o
Now maybe it is better...
function isChongHao($ary, $i, $j)
{
return ($ary[$i-1][$j] || $ary[$i+1][$j]);
}
You should probably check to ensure those indexes are set in the array beforehand, though, with an isset() call.
Assuming ary is an array
function isChongHao($ary,$i,$j) {
return (($ary[$i-1][$j] || $ary[$i+1][$j]) ? true : false);
}
Assuming ary is a function
function isChongHao($ary,$i,$j) {
return (($ary($i-1,$j) || $ary($i+1,$j)) ? true : false);
}

Categories