🚀 In this tutorial:
Now that your environment is ready, it's time to make your code speak! In this lesson, we will master echo and print—the two primary ways to send data from your server to the user's browser.
The core purpose of PHP is to transform static HTML into a living, breathing dynamic page. Think of platforms like Amazon or Instagram: the layout is consistent, but the content (prices, names, photos) changes for every user. This "magic" starts with a simple concept: Outputting Data.
The echo Statement
The echo command is the most frequently used tool in a PHP developer's arsenal. It tells the PHP interpreter to stream a string of text directly into the HTML document.
<?php
echo "Hello, World!";
?>
The browser will render Hello, World!. You can use either double quotes (" ") or single quotes (' '), as long as you remain consistent within the same statement.
Handling Line Breaks and HTML Tags
A common beginner mistake is assuming that a new line in your PHP code will create a new line on the website. Check this out:
<?php
echo "First Line
Second Line";
?>
Even though the code has a line break, the browser will display First Line Second Line on the same row. To jump to the next line on the site, you must include the <br /> tag inside your string:
<?php
echo "First Line <br /> Second Line";
?>
The print Statement
The print command works very similarly to echo, but there are two key technical differences you should know for your future interviews:
- Return Value:
printalways returns the value 1. This means it can be used in complex expressions, whereasecho(which returns nothing) will cause an error if used inside an expression. - Single Argument: Unlike
echo,printcan only take one argument at a time.
<?php
print "Mastering backend development.";
?>
Echo vs. Print: Which one should you use?
In 99% of modern web development, echo is the winner. It is marginally faster because it doesn't have a return value, and it offers more flexibility. In this Progressive PHP Course, we will stick with echo as our default.
🛠️ Practical Challenge:
Try to run a print error code (like using multiple arguments) on your local XAMPP server. Look closely at the error message in your browser. Can you identify which line caused the "Parse Error"? Understanding error messages is the first step to becoming a senior developer!
What’s Next?
Now that you know how to display text, it's time to learn how to store it. In our next tutorial, we will dive into Variables and Constants. This is where we start building real logic by giving names to our data. Don't miss it!
Nenhum comentário:
Postar um comentário