Reputation: 45
Hey fellow developers!
I'm new to PHP and backend development so as I was learning, I was facing a little "issue", where I couldn't exactly realise the difference between the opening tags (<?php) and (<?=)
The main example I was facing was the below one:
<?php
$drinks = [
"cola" => 2,
"fanta" => 3,
"sprite" => 4
];
$pastries = [
"Croissant",
"Muffin",
"Slice of Pie",
"Slice of Cake",
"Cupcake",
"Brownie"
];
?>
<h1>Welcome to the Repetitive Cafe</h1>
<h3>Drinks!</h3>
<ul>
<?php foreach ($drinks as $drink => $price):?>
<li><?="$drink costs $price dollars"?></li>
<?php endforeach;?>
</ul>
<h3>Pastries! ($2 each)</h3>
<ul>
<?php for($i = 0;$i<count($pastries); $i++):?>
<li><?= $pastries[$i] ?></li>
<?php endfor; ?>
</ul>
My question is, what is the difference between those two and why will my code not run if I add instead of between the list elements in HTML?
Thanks in advance and Happy Coding!
Upvotes: 0
Views: 54
Reputation: 53581
<?php
is the PHP code opening tag. <?=
is the echo opening tag. Both tags are closed by ?>
. The former can contain any PHP code. The latter can contain a single expression.
So this:
<?= $foo ?>
Is basically just a shortcut for this:
<?php echo $foo; ?>
Upvotes: 1