What does this syntax ( page = $page ? $page : 'default' ) in PHP mean? - php

I'm new to PHP. I came across this syntax in WordPress. What does the last line of that code do?
$page = $_SERVER['REQUEST_URI'];
$page = str_replace("/","",$page);
$page = str_replace(".php","",$page);
$page = $page ? $page : 'default'

That's the ternary operator:
That line translates to
if ($page)
$page = $page;
else
$page = 'default';

It's an example of the conditional operator in PHP.
It's the shorthand version of:
if (something is true ) {
Do this
}
else {
Do that
}
See Using If/Else Ternary Operators
http://php.net/manual/en/language.operators.comparison.php.

It's a ternary operation which is not PHP or WordPress specific, it exists in most langauges.
(condition) ? true_case : false_case
So in this case the value of $page will be "default", when $page is something similar to false — otherwise it will remain unchanged.

It means that if $page does not have a value (or it is zero), set it to 'default'.

It means if the $page variable is not empty then assign the $page variable on the last line that variable or set it to 'default' page name.
It is called conditional operator

More verbose syntax of the last line is:
if ($page)
{
$page = $page;
}
else
{
$page = 'default';
}

That's the so-called conditional operator. It functions like an if-else statement,
so
$page = $page ? $page : 'default';
does the same as
if($page)
{
$page = $page;
}
else
{
$page = 'default';
}

Related

How to set a default page id?

I am trying to display content depending on page id, however when I add nothing to the url, so just index.php I get an error saying that $p is not defined, how can I give this var a default value that's outside the switch case?
<?php
$p = $_GET['p'];
switch ($p) {
case 1:
$content1 = new login();
$content = $content1->displayLogin();
break;
case 2:
echo "ID is 2";
break;
case 3:
echo "ID is 3";
break;
default:
$content1 = new dbconnection();
$content = $content1->displayTable();
}
I understand that you want to make $p have a default value if $_GET['p'] is not defined.
You can do it like this:
$p = isset($_GET['p']) ? $_GET['p'] : 'defaultValue';
or, if you're on PHP 7:
$p = $_GET['p'] ?? 'defaultValue';
Replace:
$p = $_GET['p'];
With:
$p = !empty($_GET['p']) ? $_GET['p'] : default_id_value_here;
You can do the following:
$p = $_GET['p'] ?? <default value>; // e.g 1 or 3 etc.
Read more about it at this question: PHP syntax question: What does the question mark and colon mean?

Error with if statement to include pages in php

I have a group of pages, and I want to include one of them dependent on a variable in url, but the page is always appear is dashboard
link1 : index.php?pth=&page=dashboard
link2 : index.php?pth=modules/institution&page=inst_classification
if statement :
if (isset($page) && !empty($page)) {
$page = htmlspecialchars($_GET["page"]);
$pth = htmlspecialchars($_GET["pth"]);
}else{
$page ='dashboard';
$pth = '';
}
include ('../admin/template/'.$template_fldr.'/html/'.$pth.$page.'.php');
thanks!
You access $page before you write to it. You also never check for the existance of your pth value. Try:
if (empty($_GET['page']) || empty($_GET['pth'])) {
$page ='dashboard';
$pth = '';
}else{
$page = htmlspecialchars($_GET["page"]);
$pth = htmlspecialchars($_GET["pth"]);
}
include ('../admin/template/'.$template_fldr.'/html/'.$pth.$page.'.php');
You probably also need a / here in your include, if modules/institution/inst_classification.php is the file you are looking for:
include('../admin/template/'.$template_fldr.'/html/'.$pth.'/'.$page.'.php'); - but that is not clear from your question.
if (isset($_GET["page"]) && isset($_GET["pth"])) {
$page = htmlspecialchars($_GET["page"]);
$pth = htmlspecialchars($_GET["pth"]);
} else {
$page = 'dashboard';
$pth = '';
}
include ('../admin/template/'.$template_fldr.'/html/'.$pth.'/'.$page.'.php');

If statement evaluation and best practice

In this code the variable $controller has been initialized and used (code is from Prestashop v1.6)
$current_index = 'index.php'.(($controller = Tools::getValue('controller')) ? '?controller='.$controller : '');
What counts as not true in this if block? How is this block evaluated?
Is this considered best practice?
$current_index will equal the string index.php if Tools::getValue('controller') evaluates to false.
If you convert the block into a non-ternary operation you can see the assignment clearer:
$controller = Tools::getValue('controller');
if ($controller) {
$parameter = '?controller=' . $controller;
} else {
$parameter = '';
}
$current_index = 'index.php' . $parameter;
Ternary operations are best practice, but in the example code you've provided it's not entirely clear due to both the URL parameter assignment and the ternary operation happening on a single line.
Rewrite it as,
$controller = Tools::getValue('controller');
$current_index = 'index.php'.(($controller) ? '?controller='.$controller : '');

Pagination Problems(PHP superglobal variable issue, undefined index)

i am trying to implement pagination somewhere and i have this issue:
I have this part to change links:
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'><< Back</a> ";
which gives this error for this part:
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
It says undefined index..
Why do I get this Error?
Thanks
You should quote the array index. also use html entities.
Like this
echo " <a href='{$_SERVER['SCRIPT_NAME']}?Page=$Prev_Page'><< Back</a> ";
And its safe to check if $_GET["Page"] exists.
$Page = isset($_GET["Page"]) ? $_GET["Page"]: false;
This happens because you are missing an index in the array. $_GET is just an array, so you should check if the key exists first.
$Page = (array_key_exists('page', $_GET)) ? $_GET["page"] : false;
if($Page===false)
{
//no page
return;
}
// empty() works even if the variable doesn't exist, kind of like isset()
if(!empty($_GET['Page']) !== false) {
// Do stuff
$page = $_GET['Page'];
}

Php what is the name of this and what does it do?

I'd love to know what this means so I can google it as I see it all the time and it seems to be very useful
(($winstate==1)?'X':'O')
edit: The vars are irrelevant.
Thanks guys
That's called a ternary operator, it's PHP's only ternary operator, and it's shorthand for a conditional:
if($winstate == 1){
return 'X';
}else{
return 'O';
}
It's frequently used when the conditional test results in an assignment or returns something, in this case suppose you wanted to assign 'X' or 'O' to a variable $move, it's far more concise to write:
$move = ($winstate == 1) ? 'X' : 'O';
Look at Comparsion Operators
There's everything explained
<?php
// 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'];
}
?>

Categories