PHP code is surrounded by <?php
?>
tags, like so:
<?php
// PHP code
echo "Hello World";
?>
Every variable starts with $
character, i.e.: $name
, $products_count
.
Code inside functions is sourrounded by { }
. Functions can also have predefined arguments, i.e. $offset
.
function get_products( $min_price, $offset = 0 ) {
// getting products from DB
}
...
//both are legit calls
$products = get_products( 200 );
$products = get_products( 200, 10 );
Array is initialized by invoking array();
function:
// empty array
$products = array();
// array with predefined elements
$products = array('Roadster', 'Model X');
$products[]= 'Model S';
$products['electric cars'] = array('Roadster', 'Model X'); // [ 'electric cars'=> [ 'Roadster', 'Model X' ] ]
Let's print on the screen first element from $products
array, sub-array which key is electric cars
echo $products['electric cars'][0];
Data from web page to a PHP script can be passed throught GET or POST request. PHP script provides special superglobal variables. Two used most frequently are $_GET
and $_POST
, which are basically just associative-arrays (hashes).
// Reads 'name' parameter from URL that might look like this: http://localhost/index.php?name=John
echo $_GET['name'];
Say we want to write a script that reads name parameter from the URL, and return a greeting for that person.
<?php
echo "Hello, ".$_GET['name']."!";
?>
Save code above to index.php. Open http://localhost/index.php?name=John. Vuolia, you should see
Hello, John!
As you might already guessed .
is used to concatinate strings in PHP.