<?php
print('Hello, World!');
This code outputs "Hello, World!" to the browser.
The print statement is used to display text or variables.
<?php
print('Hello, World!');
This code outputs "Hello, World!" to the browser.
The print statement is used to display text or variables.
<?php print('Header'); ?>
Before <?php print('Hello, World!'); ?> after ...
Code outside the <?php ... ?> blocks is written to the output. You can use this to interleave HTML and PHP blocks.
<?php
$age = 42;
$message = "Your age is $age";
$fullMessage = "Welcome\n" . $message;
print($fullMessage);
You must use dollar sign '$' when using variables. There is no variable declaration. You concat strings using dot '.'.
<?php
print(htmlspecialchars('<hr>'));
Use htmlspecialchars to escape potentially dangerous content before outputting to HTML.
<?php
if ($name === "Ailish) { ... } else { ... }
Use === for equality test! Do not use == unless you know what you are doing. When using == add a comment with an explanation.
<?php
$people = ['Ailish', 'John'];
// Add a new item
$people[] = 'Paul';
// Iterate over items
foreach ($people as $index => $name) { ... }
Basic array syntax.
<?php
$student = ['name' => 'Ailish', 'age' => 22];
Using an array as a Python dictionary.
<?php
$jsonAsString = '{"name": "Ailish"}';
// Decode string
$data = json_decode($jsonAsString, true);
// Print the string representation
print($data);
// Encode back to a string
$json = json_encode(
$data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
The second argument in json_decode is true when the returned object should be an associative array.
You can customize format of the output of json_encode function using flags.
<?php
// Read from a file next to the current script.
$content = file_get_contents(__DIR__ . '/data.json');
// Write to a file next to the current script.
file_put_contents(__DIR__ . '/data.json', $content);
You can read content using file_get_contents method.
It can be used to read local and remote file as well.
For a local file use __DIR__ to keep the path relative to current file.
The file_put_contents creates a file if it does not exists. You can use the flags to append to a file.
<?php
// Get data from URL query part.
var_dump($_GET);
// Get post data.
var_dump($_POST);
// Get request method.
var_dump($_SERVER['REQUEST_METHOD']);
Reading HTTP request's data.