<h1>Calculation</h1>
<p>
<?php
echo "Hi there.\n";
$answer = 6 * 7;
echo "The answer is $answer";
?>
</p>
<p>Another paragraph.</p>
Here is how PHP works
To install PHP, check official documentation.
If you’re on Mac, you can install PHP with Homebrew.
brew install php
Run this command to ensure you have PHP installed:
brew list | grep php
You’ll need to manually add an alias as follows:
alias php='/usr/local/Cellar/php/8.0.9/bin/php'
Then check for version
php -v
A PHP script can be placed anywhere in the document. It starts with :
<?php
// PHP code
?>
In PHP, keywords (echo, if, else, etc), classes, and functions are not case-sensitive.
<?php
ECHO "Hello<br>";
echo "Hello<br>";
EcHo "Hello<br>";
?>
<?php
// This is a single-line comment
# This is also a single-line comment
?>
/*
This is a
multiple-lines
comment
*/
Variables start with a dollar sign ($) followed by the name of the variable.
A variable name
$abc = 12;
Variable scopes
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
<?php
$x = 5; // global scope
function count() {
// using x inside this function will generate an error
echo "<p>Variable x is: $x</p>";
}
count();
echo "<p>Variable x is: $x</p>";
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
<?php
function count() {
$x = 5; // local scope
echo "<p>Variable x is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x is: $x</p>";
?>
\n
doesn’t work inside of a single-quoted string<?php
echo "this is a simple string\n";
echo "You can also have embedded newlines in
strings this way as it is
okay to do";
echo "This will expand: \na newline";
// Outputs: This will expand:
// a newline
$expand = 12;
echo "Variables do $expand\n";
// Outputs: Variables do 12
There are two ways to get output in PHP: echo and print.
The differences:
echo is a language construct. It can be treated like a function with one parameter.
Without parentheses, it accepts multiple parameters.
<?php
echo "Hello world!";
print is a function. It only has one parameter, but parentheses are optional so it can look like a language construct.
<?php
print "Hello world!";
?>