Trying to understand what's going on in this PHP code? - php

I program in other languages but my job involves reading PHP and I'm trying to understand part of this view page (we use MVC).
<?
foreach ($slides as $i => $slide) {
?>
<li class="yui3-carousel-element<?=$i > 0 ? ' hidden-node' : ''?>">
<?
Why is the loop surrounded by <? and ?> ? I thought those go on either end of the entire PHP script, but instead I'm seeing them scattered throughout the whole thing.
That ternary expression seems to just be floating....it's not being echo'ed or print'ed or concatenated to anything....not to mention it weirdly seems to be comparing the number 0 to something I can't make out....it's not a string...it's an li element with no closing tag?? In php?? I'm very confused.

<? ?> are called short tags in PHP. They indicate the start and end of PHP code. The ternary is also wrapped with the short tags. That ternary is actually appending something to the class depending on whether or not the current index of $slide is greater than 0. The li is HTML and it should be closed.

<? is used as an opening tag for php-code and ?> as a closing tag. PHP can be mixed with other languages like HTML as seen in your example.
Actually it is being echo'ed, that's what the =right after the <? does. It is nothing else than a short command for echo. The other thing with the ? and : is another short form. Written out the whole thing equals if($i > 0) echo ' hidden-node'; else echo '';.
So the code adds <li>-Elements for every slide and for every slide except the first one it adds the class 'hidden-node', which most likely hides all other elements except the first one when the code gets loaded.

The <? and ?> tags are short tags saying that PHP code is inside of them. When they are closed, it goes back to simply outputting HTML.
The <?=that you see on the line is simply a shorthand for <?php echo
Personally I would have probably left the tag open at the start, then do echo on the line in the loop. What is there is the equivalent to the following:
<?php
foreach ($slides as $i => $slide) {
$hiddenElement = $i > 0 ? ' hidden-node' : '';
echo '<li class="yui3-carousel-element'.$hiddenElement.'">';

The loop is surrounded by those because it's exiting PHP code and entering HTML code. For example, you can do: <?php /*code here blah blah*/ if (...) { ?> <div>ha</div> <?php } /*more code*/ ?>. In PHP, if you don't wrap stuff with <?php ?>, then it's executed as HTML code.
That statement with <?= is a shortcut to echo'ing. It literally says <?php echo (($i > 0) ? ' hidden-node' : '' ?>.

the <? and ?> is shorthand for the php tags.
after that is clear you can see that the
<li class="yui3-carousel-element<?=$i > 0 ? ' hidden-node' : ''?>">
part is checking if $i is greater than 0 and displaying the hidden-node when it is

Related

Trouble Hiding PHP script if a DIV is present on the page

I am trying to hide the following:
<h1>aaa <?php echo HTML_SOBI::getMyCategories($mySobi, true);?> aaa</h1>
If the current div is present on the page:
<div id="bbb">
I tried to use this (Didn't work):
<div id="bbb" <?php if (condition) { echo 'style="display:none;"; } else {
echo <h1>Find More <?php echo HTML_SOBI::getMyCategories($mySobi, true);?> </h1>; } ?></div>
I thought that this would do what was expected but crashed the site in that area.
Sorry if this is newbie mistake or bad coding I am just starting out and couldn't find the right fit of code for this.
There will be tens of different eays to code this up. Critically, you need to ensure that:
you are closing any opening quotes associated with your inline style declarations
you are closing any opened html tags (<div)
These factors are essential to generate valid markup that will behave as you intend. If the following doesn't work as expected, you will need to clarify/edit your question.
<div id="bbb"<?php echo $condition ? ' style="display:none;"' : ''; ?>>
<?php
if (!$condition) {
echo '<h1>Find More ' , HTML_SOBI::getMyCategories($mySobi, true) , '</h1>';
}
?>
...
Note, I reckon the second (negated) condition is probably not needed, but I'll leave it to be demonstrative.
Another consideration is to use the condition block to assign a class to all elements that you wish to hide. If the condition is true, add the class like hiddenTag to the tags, then in your css file declare .hiddenTag { display: none; }.

Order of inclusion and interpretation for php and html

I am trying to display different content on a page based on some options.
Also, I am trying to avoid using php echo for all the html output.
I came up with the following solution accidentally, and now I'm confused about how it actually works.
test.php
<?php
function get_content() {
$page = 0;
if($page == 0)
include('page0.php');
else
include('page1.php');
}
?>
<html>
<body>
<?php echo get_content() ?>
</body>
</html>
page0.php
<?php
$link = "http://www.google.ca";
$name = "GOOGLE";
?>
<?= $name ?>
page1.php
<?php
$link = "http://www.yahoo.ca";
$name = "YAHOO";
?>
<?= $name ?>
It seems like the php interpreter would end up including html tags into a <?php ?> block when it reaches the following line, but somehow, this code works, and the outputted html is valid.
include('page0.php');
Can someone explain what exactly is going on here?
When a file is included, parsing drops out of PHP mode and into HTML
mode at the beginning of the target file, and resumes again at the
end. For this reason, any code inside the target file which should be
executed as PHP code must be enclosed within valid PHP start and end
tags.
From PHP manual, include function.

PHP's preg_match_all() to pull out all php tags

I have a large set of HTML files that I need to parse the <? and ?> tags out of, keeping in mind <?xml and the fact that an opening <?php tag doesn't need an ending tag... EOF counts too.
My regular expression knowledge is admittedly lacking: /<\?[^(\?>)]*\?>/
Example HTML:
<?
function trans($value) {
// Make sure it does not translate the function call itself
}
?>
<!-- PHP
code -->
<div id='test' <?= $extraDiv ?>>
<?= trans("hello"); ?>
<? if ($something == 'hello'): ?>
<? if ($something == 'hello'): ?>
<p>Hello</p>
<? endif; ?>
<?php
// Some multiline PHP stuff
echo trans("You are \"great'"); // I threw some quotes in to toughen the test
echo trans("Will it still work with two");
echo trans('and single quotes');
echo trans("multiline
stuff
");
echo trans("from array('test')",array('test'));
$counter ++;
?>
<p>Smart <?= $this->translation ?> time</p>
<p>Smart <?=$translation ?> time</p>
<p>Smart <?= $_POST['translation'] ?> time</p>
</div>
<?
trans("This php tag has no end");
Hoped for Array:
[0] => "<?
function trans($value) {
// Make sure it does not translate the function call itself
}
?>",
[1] => "<?= $extraDiv ?>",
[2] => etc...
No, that isn't how character classes work. Luckily you don't need to worry about that because we can use a ? to make the character class non-greedy. I'll also add a s to the end so that . can also match newlines, it usually can't.
/<\?(.*?)\?>/s
It looks like what you're looking for is lookahead and lookbehind. These regex operators basically allow you to include text in the search but omit it from the final result.
So first, you'd want to change your regex to this:
'/(?<=\<\?)[^(\?\>)]*(?=\?\>)/'
For EOF, you'd use the $ symbol. Therefore:
'/(?<=\<\?)[^(\?\>)]*(?=\?\>|$)/'
I haven't tested this but I think that should do what you're looking for, or at very least point you in the right direction.

Does it make a difference if I put a bunch code inside a single php tag vs breaking it up?

Besides personal preference, does it make any difference?
<?php
$meta = get_post_meta(get_the_ID(), 'rw_strNum', true);
'' != $meta and print "$meta";
?>
<?php
$meta = get_post_meta(get_the_ID(), 'rw_strName', true);
'' != $meta and print "$meta";
?>
as opposed to this
<?php
$meta = get_post_meta(get_the_ID(), 'rw_strNum', true);
'' != $meta and print "$meta";
$meta = get_post_meta(get_the_ID(), 'rw_strName', true);
'' != $meta and print "$meta";
?>
The first version will output an extra newline character into the generated output, since there's one between the ?> and the <?php:
?>
<?php
That is the only difference; there isn't any noticeable performance impact between the two.
Everything outside <?php ?> is treated as output. This means, that
?>
<?php
may output something. "May" because the newline after ?> is part of the tag and therefore not returned. But with something like
?>
<?php
there are two whitespace echoed. The problem is, that you cannot set any headers anymore, after something is returned to the browser.
Like knittl said, it will not make any visible difference. The only difference is it will make your HTML easier to read when you mix PHP and HTML together, for example when doing templates.
The php parser goes through the whole file regardless and I doubt encountering a closing tag and then an opening tag has any impact on parsing/speed of parsing.
Yes it makes a difference. Look at this:
<?php
$uselessvar = 1;
?>
<?php
header('Location: /'); // This will not work
?>
<?php
$uselessvar = 1;
header('Location: /'); // This will work
?>
In the first example, there is a new line between the first closing tag ?> and the second opening tag <?php. This new line is treated as an output and it's send to the client. header function could not work if any output is sent to the client before its called. That's why the first example will not work where the second will.
In a more general way, it's better to use the closing tag ?> only where you need it, to avoid such errors.
For example, you don't have to put a closing tag ?> at the end of a php file. Sometimes we see a file terminated by a closing tag then a new empty line. This new empty line has the same effect as above, and can crash/alter any script.

Can HTML be embedded inside PHP "if" statement?

I would like to embed HTML inside a PHP if statement, if it's even possible, because I'm thinking the HTML would appear before the PHP if statement is executed.
I'm trying to access a table in a database. I created a pulldown menu in HTML that lists all the tables in the database and once I select the table from the pulldown, I hit the submit button.
I use the isset function to see if the submit button has been pressed and run a loop in PHP to display the contents of the table in the database. So at this point I have the complete table but I want to run some more queries on this table. Hence the reason I'm trying to execute more HTML inside the if statement. Ultimately, I'm trying to either update (1 or more contents in a row or multiple rows) or delete (1 or more rows) contents in the table. What I'm trying to do is create another pulldown that corresponded to a column in a table to make the table search easier and radio buttons that correspond to whether I'd like to update or delete contents in the table.
<?php if($condition) : ?>
This will only display if $condition is true
<?php endif; ?>
By request, here's elseif and else (which you can also find in the docs)
<?php if($condition) : ?>
This will only display if $condition is true
<?php elseif($anotherCondition) : ?>
more html
<?php else : ?>
even more html
<?php endif; ?>
It's that simple.
The HTML will only be displayed if the condition is satisfied.
Yes,
<?php if ( $my_name == "someguy" ) { ?>
HTML GOES HERE
<?php } ?>
Yes.
<?php if ($my_name == 'someguy') { ?>
HTML_GOES_HERE
<?php } ?>
Using PHP close/open tags is not very good solution because of 2 reasons: you can't print PHP variables in plain HTML and it make your code very hard to read (the next code block starts with an end bracket }, but the reader has no idea what was before).
Better is to use heredoc syntax. It is the same concept as in other languages (like bash).
<?php
if ($condition) {
echo <<< END_OF_TEXT
<b>lots of html</b> <i>$variable</i>
lots of text...
many lines possible, with any indentation, until the closing delimiter...
END_OF_TEXT;
}
?>
END_OF_TEXT is your delimiter (it can be basically any text like EOF, EOT). Everything between is considered string by PHP as if it were in double quotes, so you can print variables, but you don't have to escape any quotes, so it very convenient for printing html attributes.
Note that the closing delimiter must begin on the start of the line and semicolon must be placed right after it with no other chars (END_OF_TEXT;).
Heredoc with behaviour of string in single quotes (') is called nowdoc. No parsing is done inside of nowdoc. You use it in the same way as heredoc, just you put the opening delimiter in single quotes - echo <<< 'END_OF_TEXT'.
So if condition equals the value you want then the php document will run "include"
and include will add that document to the current window
for example:
`
<?php
$isARequest = true;
if ($isARequest){include('request.html');}/*So because $isARequest is true then it will include request.html but if its not a request then it will insert isNotARequest;*/
else if (!$isARequest) {include('isNotARequest.html')}
?>
`
<?php if ($my_name == 'aboutme') { ?>
HTML_GOES_HERE
<?php } ?>
I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.
In the php
<?php
$var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';
if ($var1 == 'Alice') {
$html = file_get_contents('/path/to/file.html'); //get the html template
$template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
$template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
$html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
}
echo $html_output;
?>
In the html (/path/to/file.html)
<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>
The output of this would be:
Alice ate apples for lunch with Bob.

Categories