Hide html when included inside php if condition - php

I would like to present some php with the help of html formatting.
My purpose is to print:
Life status: dead (1850 in New-York)
or (if not dead):
Life status: alive
The place and date should only by printed if the condition $life_status is set to "dead".
The following code works for the dead situation but not for the alive one.
<h3>Title</h3>
<ul>
<li>Life status: <?php echo $life_status;?>
<?php if($life_status="dead"):?>
(<?php echo $date_death; ?> in <?php echo $place_death; ?>).
</li>
<?php endif; ?>
</ul>
For the alive sitation, I obtain:
Life status: Alive ( in ).
How can I applied the php condition on "( in)."?

Your operator for checking if $life_status is dead is wrong. It is a single equal and should be double. Code below reflects these changes and implements what #AmericanUmlaut correctly suggested in the comment above to make your html actually valid.
<h3>Title</h3>
<ul>
<li>Life status: <?php echo $life_status;?>
<?php if($life_status == "dead"):?> // This maybe the issue, wrong operator used to evaluate.
(<?php echo $date_death; ?> in <?php echo $place_death; ?>).
<?php endif; ?>
</li>
</ul>

You are using the wrong operator. = is assignment, == tests equality.
<h3>Title</h3>
<ul>
<li>Life status: <?php echo $life_status;?>
<?php if($life_status=="dead"):?> // == here instead of =
(<?php echo $date_death; ?> in <?php echo $place_death; ?>).
<?php endif; ?>
</li>
</ul>
(Note that I also moved the outside of the if block to address the issue I noted in my comment.)

In Php strings are not compared directly and may not give the results which are intended. Therefore, using strcmp(); function will do the work. It returns 0 when 2 strings compared are equal and is a case sensitive function.
In your case:
<h3>Title</h3>
<ul>
<li>
Life status: <?php
echo ( !strcmp($life_status,"dead") ) ? 'Dead ( '.$date_death.' in '.$place_death.' ).' : 'Alive' ;
?>
</li>
</ul>
I have used the Php Ternary operator known as Shorthand if/else.
The ! will reverse the 0 to 1 if its true to show the Dead output and else will show the Alive output.
Php Ternary : http://php.net/manual/en/language.operators.comparison.php
Php strcmp() : http://php.net/manual/en/function.strcmp.php
I hope it helps :)
Regards,
SA

Related

open&close php tags on each line, within arrays, functions

I collaborate with a web-programmer on a php project based in kirby cms, and he wants to open and close every line as such:
<main>
<?php /*php code here/* ?>
<?php /*more php here*/ ?>
...
Trying to follow this style, I found some errors in my code. The first is that it seems I canNOT do this in the middle of an array as such:
BAD CODE
<?php $oo = array( ?>
<?php 'h' => 100, ?>
<?php 'v' => 100, ?>
<?php ); ?>
but I can do it in the middle of a foreach loop as such:
<?php foreach ($p as $subp): ?>
<div id='<?= $subp->title() ?>'>
<?php endforeach; ?>
Are there any other cases such as array in which I canNOT do this?
/edit
According to the answer, there can only be tag-breaks within 'foreach', 'while', or 'if' blocks.
How about a 'foreach', 'while' or 'if' within a function? is that 'legal'?:
<?php
function myFunction($arg){
if($arg === 'this'): ?>
<?= '<p>yep</p>' ?>
<?php else: ?>
<?= '<p>nop</p>' ?>
<?php endif;
};
?>
And how about nesting if within foreach within function?:
<?php
function myFunction($arr){
foreach($arr as $val): ?>
<p><?= $val ?> <p>
<?php if($val === 'this'): ?>
<?= '<p>yep</p>' ?>
<?php else: ?>
<?= '<p>nop</p>' ?>
<?php endif;
endforeach;
};
?>
edit/
Thank you
you cannot "break out of php" mid statement. wline defining an array for example you cannot close the php tags. The only time when you can "break out" of php is between opening and closing a loop or an if/else statement. This actualy does not break the statement as <?php foreach: ?> is a complete statement whereas <?php foreach{ ?> is not. Here some examples of what you can do:
<?php if($this!=$that): ?>
{something}
<?php endif ?>
<?php foreach($things as $thing): ?>
{something}
<?php endforeach ?>
<?php $while($this): ?>
{something}
<?php endwhile ?>
I think you get the message. you must have complete statements within php tags, without interruptions.
P.S. Also avoid using the shorthand <? instead of <?php at all cost, moving your project to a different hosting or an upgrade of your hosting might break your project as per default short tags are not activated. <?= ?> shorthand is safe as this is unaffected by the setting for newer php versions.
P.P.S Do not listen to the guy who wants php in one line, this will make your code hard to read and maintain. Stand strong and write beautiful code :)
UPDATE: (after the update on the question from #Jaume Mal)
I did not mean the examples in my answer as exclusive but as examples of statements that are complete vs statements that are incomplete. (I also forgot to mention closing php tags mid fuction, wich also work but I despise and woudl strongly advise against.) So for example <?php function foo(){ is a complete statement of starting a function but (as the other cases with loops etc..) it needs a closing statement, in this case }. This is true for if / else or foreach and so on:
<?php if($this){ ?>
some code
<?php } ?>
is a valid code, as the code pieces within the php tags are complete statements.

How to set condition in following code for marking current page in pagination?

I am trying to set a condition for php- mysql pagination so that it can change the current page "li" to "li class="active" " to mark the current selected page. I am new to php and searching for such pagination tutorial but no luck.
I have done so far what is working but not able to mark selected page. Here $id is for detecting the current page id. How can I set if condition ( or other) so that I can mark the current page item in the pagination? Thousands thanks for helping me.
<ul class="pagination">
<?php if($id > 1) {?> <li>Previous</li><?php }?>
<?php
for($i=1;$i <= $page;$i++){
?>
<?php
if ($id>1)
{ ?>
<li class="active"><?php echo $i;?></li>
<?php }
?>
<!-- <li><?php echo $i;?></li> -->
<?php
}
?>
<?php if($id!=$page)
//3!=4
{?>
<li>Next</li>
<?php }?>
</ul>
You could change your for loop from
<?php
for($i=1;$i <= $page;$i++){
?>
<?php
if ($id>1)
{ ?>
<li class="active"><?php echo $i;?></li>
<?php }
?>
<!-- <li><?php echo $i;?></li> -->
<?php
}
?>
to:
<?php
for($i=1;$i <= $page;$i++){
$class=($i==$id)? ' class="active"' : '';
echo '<li'.$class.'>'.$i.'</li>';
}
?>
If I've understood your code properly, $page represents total pages and $id represents the current page, this will set the current page number as the active class and leave the other pages without the class
Assuming that $id is the current page number, and that $page is the total number of pages, you need to highlight only one by doing the following in your loop:
if($i==$id) // highlight
else // don’t highlight
Your main errors are that you didn’t test whether $i==$id, and you didn’t have an alternative unhighlighted version.
I really think that you should simplify your code by separating your logic from the HTML. It becomes very unreadable otherwise, and very hard to manage.
I have taken the liberty of doing just that. This way you can see where the logic does the hard work, an you only need to print the results in the HTML.
<?php
$id=3; // test value
$page=20; // test value
$li=array(); // temporary array for convenience
$template='<li%s>%s</li>';
if($id>1) $li[]=sprintf($template,'',$id-1,'Previous');
for($i=1;$i<=$page;$i++) {
if($i==$id) $li[]=sprintf($template,' class="active"',$i,$i); // Current
else $li[]=sprintf($template,'',$i,$i);
}
if($id<$page) $li[]=sprintf($template,'',$id+1,'Next');
$li=implode('',$li); // convert to string for printing
?>
<ul class="pagination">
<?php print $li; ?>
</ul>
You will also see two techniques to make things easier:
I use an array as a temporary container. It is easier to add items this way and then to implode it into a string afterwards
sprintf makes it easier to define a template string, so you can manage the HTML component more easily, and fill in the gaps when the time comes.

Site prints all PHP instead of using it

another problem. I'm making a CMS and I want the login link to disapear when I want to. So I can configure it in my adminCP. When I "flip the switch" my configfunctions.php changes $login to true.
To use it I'm doing:
<?php if($loginenabled = true) { '<li><span class="mmLogin">Login</span></li>' }; ?>
but my site literally prints ALL PHP, also when I do other PHP. So my site looks like:
Home, About us, <?php if($loginenabled = true) { 'login' }; ?>
Does anyone know how to solve it?
Wesley
You can't output HTML code by simply creating a string. To write output, you can use the echo statement:
<?php if ($loginEnabled == true) {
echo '<li><span class="mmLogin">Login</span></li>';
}; ?>
Note the semicolon at the end of the single quotes ('). You can also use PHP's alternate syntax for control structures for cleaner code:
<?php if ($loginEnabled == true): ?>
<li><a href="sample-login.html" class="login">
<span class="mmLogin">Login</span>
</a></li>
<?php endif; ?>
The above will accomplish the same thing. Also note that ($loginEnabled = true) is always true, since = is an assignment operator. To check if $loginEnabled is true, use:
if ($loginEnabled == true)
You can also shorten it to simply:
if ($loginEnabled)
Read more on assignment operators, comparison operators, and the if statement.

PHP separating multiple while loops in sequence

this is my first post here. I spent all of yesterday searching the net for an answer, but I think I've got a fairly unusual application of the while loop here so I didn't have much success.
Essentially I have a several categories, for example titled "Kosove" and "Shqiperi". Each of these has a number of sub-sections. Those sub-sections may or may not have content inside them.
I'm using while loops to display the sub-sections, providing they DO have content inside.
This is my code:
<ul>
<?php while(osc_has_list_regions($country = 'kv') ) { ?>
<li><?php echo osc_list_region_name(); ?> <em>(<?php echo osc_list_region_items(); ?>)</em></li>
<?php } ?>
</ul>
Notice the " $country = 'kv' " identifies the category as 'Kosove' in this case.
What is generated is:
Prishtine(1)
Vushtrri(1)
Which is fine.
The problem occurs when I want to also display the subsections for another category, e.g. Shqiperi. The code for this:
<ul>
<?php while(osc_has_list_regions($country = 'kv') ) { ?>
<li><?php echo osc_list_region_name(); ?> <em>(<?php echo osc_list_region_items(); ?>)</em></li>
<?php } ?>
</ul>
<br><br>
<ul>
<?php while(osc_has_list_regions($country = 'al') ) { ?>
<li><?php echo osc_list_region_name(); ?> <em>(<?php echo osc_list_region_items(); ?>)</em></li>
<?php } ?>
</ul>
Again notice the " $country = 'al' " identifies the category as 'Shqiperi' in this case.
What is generated is:
Prishtine(1)
Vushtrri(1)
Prishtine(1)
Vushtrri(1)
Which is not correct. The second part of the code has ignored the 'al' and just repeated the previous while loop content (i.e. the subsections for 'kv').
It SHOULD read:
Prishtine(1)
Vushtrri(1)
Berat(1)
As 'Berat' is the appropriate subsection for the 'Shqiperi' category.
If I have " $country = 'al' " as the first while loop condition, then it shows:
Berat(1)
Berat(1)
So obviously the order is important. It seems that the previous loop hasn't been properly closed.
I'm pretty new to PHP and I'm not even sure if I'm using the while loop appropriately here. Any suggestions how to fix this would be hugely appreciated.

highlight current page link in opencart or any php

Im just learning open cart, but I think this question could be answered by anyone with good php knowledge.
I am simply attempting to highlight the a link when only on that page, but it doesnt seem to work
<?php $tickets = 'index.php?route=product/category&path=600'; ?>
<ul>
<li>Limerick FC</li>
<li><a href="<?php echo $tickets; ?>" <?php
if (strpos($_SERVER['PHP_SELF'], $tickets )) echo "class=\"current\" ";
?> > Tickets </a></li>
<li>Shop</li>
</ul>
I know the variable $tickets is fine because the link goes to where its supposed to go, and I know the class current is fine because it works for the third li which is shop.
Am I using strpos correctly?
I think you should use basename($_SERVER['REQUEST_URI']);.
<a href="<?php echo $tickets; ?>" <?php echo (basename($_SERVER['REQUEST_URI']) == $tickets) ? '"class=\"current\"' : ""; ?>>Tickets</a>
it would be more better if you declare basename($_SERVER['REQUEST_URI']) in variable.
strpos() returns false if the string matches at char 0 - which the above does.
Use indentical comparisons === for a true outcome.
As a note, i've used substr_count() in the past for similar circumstances without needing identical comparison!

Categories