Loop with curly brackets causes wrong output - php

I created 2 simple examples:
First example:
<?php $arr = array(1,2,3,4,5); ?>
<?php foreach ($arr as $element) ?>
<?php { ?>
<?php echo $element; ?>
<?php } ?>
output:
5 //Is this result wrong?
Second example:
<?php $arr = array(1,2,3,4,5); ?>
<?php foreach ($arr as $element) { ?>
<?php echo $element; ?>
<?php } ?>
output:
12345
What did I miss about the PHP syntax?
I know that there is an alternative foreach syntax, but in my opinion both shown examples should result in the same output. (Code tested with PHP version: 5.6.12)
Edit:
I know the tags are not needed in every line.
To be more precise: I want to know why the two examples give me 2 different results?

Based on the output, my guess is that:
<?php $arr = array(1,2,3,4,5); ?>
<?php foreach ($arr as $element) ?>
<?php { ?>
<?php echo $element; ?>
<?php } ?>
is being interpreted as:
<?php
$arr = array(1,2,3,4,5);
foreach ($arr as $element);
{
echo $element;
}
?>
Looks like a bug in the interpreter? See comments by Rizier123:
Not a bug: stackoverflow.com/q/29284075/3933332
The brackets after the foreach()/Do nothing here/; is just a statement-group: php.net/manual/en/control-structures.intro.php
Anyways, the code looks atrocious with the way you have written it. Please opt for cleaner code.
Reading through the comments under the question I think Jon Stirling explain this symptom the best:
Just guessing, but perhaps the ?> in the first example is actually being taken as the statement end (loops can be used without braces). At that point, the loop has happened and $element is the last value. Then the braces are just take as a code block which you echo, which is 5.

Over using <? php> is your problem.
You are completing the foreach context before outputting the result and not doing that in the second.
Look at your examples carefully and you should see what you are doing differently.

I don't know why you use so many php tags, but that's why it doesn't work!
try this:
<?php $arr = array(1,2,3,4,5);
foreach ($arr as $element)
{
echo $element;
} ?>

You don't need to use <?php and ?> every single line simply do:
<?php
$arr = array(1,2,3,4,5);
foreach ($arr as $element) {
echo $element;
}
?>
Or alternative syntax:
<?php
$arr = array(1,2,3,4,5);
foreach ($arr as $element)
{
echo $element;
}
?>
Or
<?php
$arr = array(1,2,3,4,5);
foreach ($arr as $element):
echo $element;
endforeach;
?>
When you are doing this:
<?php foreach ($arr as $element) ?>
<?php { ?>
<?php echo $element; ?>
<?php } ?>
PHP loops nothing because it sees
foreach ($arr as $element)
{
}
echo $element;

Related

Foreach in foreach [PHP]

Actually I work with PHP framework Codeigniter and I want to compare value from first foreach to second one, but I'm getting an error. Example here:
<?php foreach($posts->result() as $post): ?>
(html content)
<?php foreach($tags->result() as $tag) {
if($tag->id_users == $post->id_users) echo $tag->tag_name;
} ?>
(html content)
<?php endforeach; ?>
When I compare $post->id_users inner second foreach I'm getting error, how can I get around this?
Its better to avoid loop inside a loop
$tag_ids = array();
foreach($tags->result() as $tag) {
$tag_ids[] = $tag->id_users;
}
foreach ($posts->result() as $key => $post) {
if(in_array($post->id_users, $tag_ids)) {
}
}
You don't close the second foreach. For eg
<?php foreach($posts->result() as $post): ?> foreach1
(...some html)
<?php foreach($tags->result() as $tag) { if($tag->id_users == $post->id_users) echo $tag->tag_name; } ?> //foreach2
(...some html)
<?php endforeach; ?>
<?php endforeach; ?>
You should not use $posts->result() and $tags->result() inside foreach loop. Because it will go to check for every time while foreach is live.
Overall it decrease the performance of script.
<?php
$posts = $posts->result();
$tags = $tags->result();
foreach($posts as $post) {
?>
<< Other HTML code goes here >>
<?php
foreach($tags as $tag) {
if($tag->id_users == $post->id_users) {
echo $tag->tag_name;
}
?>
<< Other HTML code >>
<?php
}
}

PHP : Get 9 random value from array

I'm struggling to get 9 random values from an array, I have this php code which works fine but returns all the values. I need to only select 9 random ones with an foreach preferably.
<?php
foreach($gallerystreamobjects as $smallgallery) {
$smallgalleryArray = $smallgallery->GalleryPictures;
}
$arr = explode(",", $smallgalleryArray);
foreach($arr as $value)
{
?>
<a href="cms/uploads/<?php echo $value;?>" class="swipebox">
<div class="gallery-item-small" >
<div style="background-image:url('cms/uploads/<?php echo $value;?>')"></div>
</div>
</a>
<?php
}
?>
The function array_rand() will solve your problem:
$randomKeys = array_rand($arr, 9);
foreach($randomKeys AS $key){
$value = $arr[$key];
//do whatever you like
}
I managed to use an quick and easy way to do this. Not that its the right way, but ja, so I tried array_rand() but I kept on getting errors on it in its most basic way, I found out it was to do with the values actually going missing. Here is my current solution :
<?php
$smallgalleryArray = $gallerystreamobjects[0]->GalleryPictures;
$arr = explode(",", $smallgalleryArray);
shuffle($arr);
$count=0;
foreach($arr as $value) {
$count++;
if($count<10){
?>
<a href="cms/uploads/<?php echo $value;?>" class="swipebox">
<div class="gallery-item-small" >
<div style="background-image:url('cms/uploads/<?php echo $value;?>')"></div>
</div>
</a>
<?php
}
}
?>

whats the best way to echo a php tag inclusive in a while loop?

Edit |
This is a simple url...
The issue is I have to echo it in a while loop.
Which means I cant use php tags.
MY cancatenation sucks... I tried it for hours (noob) Please help
The issue is I have to echo it in a while loop. Which means I cant use php tags.
It doesn't mean that.
<?php
while ($condition) {
?>
Edit |
<?php
}
?>
(But if you have a list of links, then use list markup (ul/ol/li) not | characters).
try something like this
echo 'Edit'
It's pretty simple:
<?php
While(condition){
?>
Edit
<?php
}
?>
I would suggest to "prepare" the whole element in php. Something like this:
foreach ($arr as $key) {
print 'Edit';
}
<?php
while ($condition) {
echo 'Edit';
}
?>
You can also use heredoc syntax.
Sidenote, I would collect them all and echo it out once in the end
$text = '';
while ($foo) {
$text .= 'Edit';
}
echo $text;
// or heredoc
$text = '';
while ($foo) {
$text .= <<<_HTML
Edit
_HTML;
}
echo $text;
// or array
while ($foo) {
$data[] = 'Edit';
}
if(!empty($data)){
echo '<p>'.implode('</p><p>',$data).'</p>';
}
if it is a template file in php then always use this type of syntax
code:
<?php
$i=0;
while($i<10) : ?>
<div><?php echo $i;?></div>
<?php
$i++;
endwhile;?>

A colon after foreach loop statement cause an error

I got below code
<?php foreach ( $resultsb as $optionb ) : ?>
<option value="<?php echo $optionb->bID; ?>"><?php echo $optionb->book;?></option>
<?php endforeach; ?>
i know how the foreach is working here but i didn't get the : after the php statement what does the : do after the foreach statement
<?php foreach($resultsb as $optionb) : ?>
...
<?php endforeach; ?>
is nothing else then:
<?php foreach($resultsb as $optionb) { ?>
...
<?php } ?>
IMO it enhances the readability in files with a lot of html/xml etc.
Try like This
$a = array(1, 2, 3, 17);
foreach ($a as $v) {
echo "Current value of \$a: $v.\n";
}
Your code is true. You must check your array. Error not related to ":". It related to your $resultsb.

How can I do a foreach loop using php dictionaries?

I am trying to make a php navbar sort of thing. I have the html code and what I want to do is to use a php dictionary ("Home"=>"http://www.domain.com/") and turn it into html code.
<ul>
<?php foreach ($links as $title => $url): ?>
<li><?php echo htmlentities($title); ?></li>
<?php endforeach; ?>
</ul>
foreach($arr as $key=>$value) {
// your code here
}
I have no idea how you want to make your navbar, but with any knowledge of HTML you should be able to go from here.
foreach (dict as $key => $value){
echo "<a href='$value'>$key</a>";
}
Fastest
<?php
foreach($array as $name => $link){
echo '',$name,'\n';
}
?>
Easier to read and understand but slower
<?php
foreach($array as $name => $link){
echo "<a href='$link'>$name</a>\n";
}
?>
I don't know if i understand the question but you can use an hash like this:
<?php
$navBar = array(
"Home" => "http://www.domain.com/",
"Info" => "http://www.domain.com/info/",
);
foreach($navBar as $key => $val){
echo "<li>$key => $val<li>";
}
?>

Categories