What is meant by this php statement - php

Hello I have read following php statement from a blog but I am unable to understand its meaning. Is it treated as if condition or any thing else? Statement is
<?= ($name== 'abc' || $name== 'def' || $name== 'press') ? 'inner-pagehead' : ''; ?>

You can read this as:
if($name=='abc' || $name=='def' || $name=='press') {
echo 'inner-pagehead';
} else {
echo '';
}
The <?= is the echo() shortcut syntax, then the (test)?true:false; is a ternary operation

It is saying that if $name is any one of those 3 values ("abc","def", or "press"), then display the text "inner-pagehead". Otherwise, don't display anything.

This is what I would call a poorly written Ternary condition. it basically echos 'inner-pagehead' if the $name variable matches any of the three conditions. I would have done it like this:
<?php
echo in_array($name, array('abc', 'def', 'press')) ? 'inner-pagehead' : '';
?>
Or, even better:
// somewhere not in the view template
$content = in_array($name, array('abc', 'def', 'press')) ? 'inner-pagehead' : '';
// later, in the view template
<?php echo $content; ?>

Related

PHP - Get part of $_GET string

I currently have this:
$thispage = $_SERVER['QUERY_STRING'];
if($thispage == "i=f" || $thispage == "i=f&p=t" ) echo "active";
Although, the "i=f&p=t" is not correct, as the page looks like this:
i=f&p=t&cid=71&id=161
My question is, how can I do so if just the first part of the $_GET string is correct (in this example "i=f&p=t) then it will match $thispage. I don't want it to check for & $_GETs
I want $thispage to work with other pages than just the example above. I only want to check the first part of the string. Not what comes after &
I'd go for parse_str function:
parse_str($_SERVER['QUERY_STRING'], $thispage);
if ( $thispage['i'] === 'f' OR ($thispage['i'] === 'f' AND $thispage['p'] === 't') ) {
echo 'active';
}
Update:
I don't want it to check for & $_GETs
I don't know why you don't want to use $_GET if it's the Query String that you're working on that now, but you can do the following as well, which makes more sense:
if ( $_GET['i'] === 'f' OR ($_GET['i'] === 'f' AND $_GET['p'] === 't') ) {
echo 'active';
}
Did you mean this?
if(strpos($_SERVER['QUERY_STRING'], 'i=f') !== false) {
echo "active";
}
If that is truly what you want to do, then you are actually checking if
if (substr($_SERVER['QUERY_STRING'], 0, 7) === "i=f&p=t")
You can access the url parameters directly by using the $_GET array.
var_dump($_GET);
If you want to use $_SERVER['QUERY_STRING'] you can use the parse_str function to parse the query string:
<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>

how to nest if and else statement using ternary operator in PHP?

am confused with using this ternary operator, i can easily get 1 level if and else
e.g
($blah == $blah) ? blahblah : blahblahblah;
but what if the condition is like this?
if($blah == blah1)
{
echo $blah1;
}
else if($blah == blah2)
{
echo $blah2;
}
else
{
echo $blah;
}
how to convert this using ternary operator ?
<?php echo $blah == 'blah1' ? $blah1 : ($blah == 'blah2' ? $blah2 : $blah); ?>
Notice how the else is wrapped in parenthesis. This can be done again and again, although it becomes confusing to read.
Nested ternaries are a bad idea. They're provided for brevity. If you have nested conditions, you by definition do not have brevity.
Some folk don't even like their use when you have a concise statement. Personally I find the following more clear and readable than the if-based alternative.
echo $success ? 'Success' : 'Failure';
But I would hesitate to do anything more complex than that.
($blah == $blah1) ? $blah1 : (($blah == $blah2) ? $blah2 : $blah);
It would become:
echo (($blah == $blah1) ? $blah1 : (($blah == blah2) ? $blah2 : $blah);

Using Same If Else Statement Multiple Times

I'm doing this...
<?php $term = ucfirst($_GET['term']);?>
And doing this multiple times on the page:
<?php if (empty($term)) echo 'X'; else echo $term; ?>
Is there a better way to go about this?
You can specify the placeholder value when you first assign the value:
<?php $term = ucfirst($_GET['term']) or $term = "X"; ?>
(Works because the OR has lower precedence than the assignment.)
Then just print that variable henceforth:
<?= $term ?>
It will contain either the input value, or your X.
ternary operator :
$term = (empty(ucfirst($_GET['term']))) ? echo 'X' : $_GET['term'];
Declare a function
function doTerm()
{
$term = ucfirst($_GET['term']);
if (empty($term)) echo 'X'; else echo $term;
}
so you can call it like
doTerm();
whenever you need it to test and echo.
<?php
$term = isset($_GET['term']) ? ucfirst($_GET['term']) : 'X';
echo $term;
//...
?>
If you don't need it anywhere else than you could make it even shorter :-)
echo (isset($_GET['term']) ? ucfirst($_GET['term']) : 'X');
Ternary syntax can work easily here:
Using short hand tags:
<?=empty($term) ? 'X' : $term ?>
or long hand:
<?php echo empty($term) ? 'X' : $term ?>
you can use Conditional Operator like
echo ($term!=null)? 'x' : $term;

Simple PHP issue

I'm new to shorthand conditional statements and I can't for the life of me work out how to do it, here's the simple code I have:
<?php
function evolve_nav($vals) {
echo '<'.$vals['type'] !== '' ? ''.$vals['type'].'' : 'darn''>';
}
?>
Does anyone know why this doesn't return anything and results in an error?
You just forgot some brackets:
function evolve_nav($vals) {
echo '<'.(!empty($vals['type']) ? $vals['type'] : 'darn').'>';
}
evolve_nav(array('type' => 'foobar'));
evolve_nav(array('not' => 'showing'));
echo '<' . ($vals['type'] !== '' ? $vals['type'] : 'darn') .'>';
$descriptiveVariableName = $vals['type']!=='' ? $vals['type'] : 'darn';
// View code
echo "<$descriptiveVariableName>";
''.$vals['type'].'' is superfluous, make it $vals['type']
'darn''>' those are two string literals without any operator (or anything) between them -> syntax error.
In this case I'd rather not use string concatenation (i.e. using the dot-operator like 'xyz' . $a ) but "pass" multiple parameters to echo.
echo
'<',
''!==$vals['type'] ? $vals['type'] : 'darn',
'>';
or using printf
printf('<%s>', ''!==$vals['type'] ? $vals['type'] : 'darn');

Two if statements using ternary condition

The title seems confusing but this is my first time using ternary conditions. I've read that ternary is meant to be used to make an inline if/else statement. Using no else is not possible. Is it true?
I want to change this with ternary condition for practice
if (isset($_SESSION['group']
{
if ($_SESSION['item'] == 'A')
{
echo "Right!";
}
}
It has two if statements only. The second if is nested with the other. I've also read that to make a no else possible for ternary, it just have to be set to null or empty string.
It's a bad example because you can use an AND-operator on the nested if:
$result = isset($_SESSION['group'] && $_SESSION['item'] == 'A' ? true : false;
Of course you can nest ternary operator, too:
$result = isset($_SESSION['group'] ? ( $_SESSION['item'] == 'A' ? true : false ) : false;
with echo
echo isset($_SESSION['group'] ? ( $_SESSION['item'] == 'A' ? "Right!" : "false" ) : "false";
echo (isset($_SESSION['group']) && $_SESSION['item'] == 'A') ? "Right" : ""
Better still (readable, maintainable), use:
if (isset($_SESSION['group']) && $_SESSION['item'] == 'A')
{
echo "Right!";
}
isset($_SESSION['group'] ? (if ($_SESSION['item'] == 'A') ? echo "Right" : null) : null
Try this, I think it might work =].
For further reading on ternary conditions in Java/ whatever you're using look at http://www.devdaily.com/java/edu/pj/pj010018
You can nest two ternary statements as this example:
echo (isset($_SESSION['group']))?($_SESSION['item']== 'A')?'Right!':null:null;
Did you know you can do this as well? (isset($_SESSION['group']) && ($_SESSION['item']=='A')) &&($result$c= 1); or echo (isset($_SESSION['group']) && ($_SESSION['item']=='A')) ? 'Hello!':'World!';

Categories