Using Same If Else Statement Multiple Times - php

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;

Related

Adding arrays in json_encode and count them

I want to count all Arrays together but dont know my Problem
$output = array(
'facebook'=> isset($finfo[0]) ? $finfo[0]->total_count : NULL,
'twitter'=> isset($tinfo->count) ? $tinfo->count : NULL,
'delicious'=> isset($dinfo[0]) ? $dinfo[0]->total_posts : NULL,
'pinterest'=> isset($pinfo->count) ? $pinfo->count : NULL,
'googlePlus'=> isset($gplus[0]['result']) ? $gplus[0]['result']['metadata']['globalCounts']['count'] : NULL
);
function getSocialCount($output){
return json_encode($output[facebook]) + json_encode($output[twitter]) + json_encode($output[pinterest]) + json_encode($output[googlePlus]);
}
<div>All: <?php echo getSocialCount(); ?></div>
Am I writing the Syntax wrong?
Yes, your function expects one parameter and you are not giving it any.
Change:
<?php echo getSocialCount(); ?>
to:
<?php echo getSocialCount($output); ?>
Maybe you should add your array $output into your function..
<?php echo getSocialCount($output); ?>

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

What is meant by this php statement

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

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

array_key_exists in a foreach

Hi There I am running this code currently,
<?php foreach($search_results as $rslt) : ?>
<?
$code = $rslt['code'];
if(array_key_exists($code, $short_list)) {
$set = "set";
}
?>
<div class="row <? echo $set;?>"></div>
What I am trying to achieve is that if the array equals the $rslt['code'] then give the div the class of set otherwise don't the array I checking against looks like this,
Array
(
[849650047] => Y
[849652539] => Y
[849652774] => Y
[849656557] => Y
[849652014] => Y
)
However every time I loop all my divs get set with the 'set' class? It should only be where the array_key equals the current $code
Well, they are all set, because you're never initializing the $set variable:
<?php foreach($search_results as $rslt) : ?>
<?
$set = '';
$code = $rslt['code'];
if(array_key_exists($code, $short_list)) {
$set = "set";
}
?>
<div class="row <? echo $set;?>"></div>
Also, just use isset() instead of array_key_exists (it's more efficient, and less wordy):
if(isset($short_list[$code])) {
$set = "set";
}
just add unset($set); at end of your loop. Or you can do something like...
<?php foreach($search_results as $rslt) : ?>
<div class="row <? print array_key_exists($rslt['code'], $short_list)? 'set':''; ?>"></div>
<?php endforeach; ?>
Avoid the alternate control structure syntax in PHP. It's ugly and makes your code more difficult to maintain in the long run. Also try to avoid excessive context switching with <?php ?>; it makes your logic needlessly difficult to follow.
<?php
foreach ($search_results as $result) {
$set = isset($short_list[$result['code']]) ? ' set' : '';
echo "<div class=\"row$set\"></div>";
}
Note that isset() will return false if the key exists in the array, but its value is null. Something to watch out for if you want the "set" class applied even if the value of $short_list[$result['code']] is null.

Categories