Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. PHPBeginner - PHP Beginner Summary

PHP Beginner Summary - Images: Japanese

Hey everyone!

This article is the full summary of the PHP Beginner series. If there's anything you've forgotten along the way, give it a quick review here.

PHP Blocks

PHP is designed to be embedded in HTML, so PHP code must be wrapped in a PHP block. The opening tag is <?php and the closing tag is ?>. One important thing to note: if a file ends with a PHP block, you should leave out the closing tag — keeping it in can cause errors.

<?php
    echo 'Hello world';
?>
<?php
    // For files that end with a PHP block, it's safer to omit the closing tag.

For more details, see this article.

Strings

In PHP, you create a string by wrapping text in either single quotes (') or double quotes ("). Use single quotes when you want the text treated literally. Use double quotes when you want escape sequences or variable interpolation to work. When interpolating a variable, put a space on each side of it, or wrap it in {}.

<?php
    echo 'Hello world';
<?php
    $txt = "Hatsune Miku";
    echo "I love $txt .";
    echo "I love{$txt}.";

For more details, see this article.

Escape Sequences

Using \ lets you escape the special meaning of a character and treat it as a plain character.

<?php
    echo "<p class=\"hoge\">This is a p element with the class name 'hoge'!</p>";

Things like newlines can also be represented using escape sequences. The following reference lists all the available escape sequences.

http://php.net/manual/en/regexp.reference.escape.php

For more details, see this article.

Outputting Text and var_dump()

To output text, use echo or print. echo is slightly faster, so it's generally preferred unless you have a specific reason to use print. When you want to inspect the detailed contents of a value or an array, var_dump() is the way to go.

<?php
$txts = ['Miku', 'IA'];
var_dump($txts);

echo 'Hello world';

For more details, see this article.

Comments in PHP

For a single-line comment, write // or # at the start of the line. A single-line comment ends at either a newline or the PHP block closing tag. For multi-line comments, wrap them between /* and */. Unlike single-line comments, multi-line comments do not end at the PHP block closing tag — keep that in mind.

<?php
// This is a comment.
# This is also a comment.
// This part is a comment. ?>But this is outside the PHP block, so it's not a comment — it gets output as-is.

<?php
/*
This is a comment.
You can span multiple lines.
*/

/*
Multi-line comments do not end at the PHP closing tag.
?>nope
*/

For more details, see this article.

Statements, Semicolons, and Indentation

In PHP, a single small unit of processing is called a statement. Every statement must end with ;. Newlines, spaces, and tab characters are generally ignored in PHP, so you're free to indent however you like. If there's a coding style guide in place, follow that for your indentation.

For more details, see this article.

Error Handling and php.ini

PHP's configuration file php.ini controls how errors are reported. Setting error_reporting = E_ALL and display_errors = On tells PHP to display error output. To find where your php.ini file is located, run phpinfo() and look for the Loaded Configuration File entry.

For more details, see this article.

Variables

In PHP, variables start with $. Assignment uses =, and the value on the right side is assigned to the variable on the left — keep that direction in mind. PHP doesn't require variable declarations or explicit type definitions. The naming rules for variables are as follows.

  • Use one or more alphanumeric characters or underscores (_).
  • The first character must not be a digit.
  • Names are case-sensitive.
  • Reserved words cannot be used.
<?php
$test1 = 1;
$test2 = 2;

echo $test1 + $test2;

For more details, see this article.

include() and require_once()

To include another file, use include() or require_once(). The common practice is to use include() for general files and require_once() for important files like function definitions.

<?
include('./header.php');
require_once('./functions.php');

For more details, see this article.

Basic Operators and String Concatenation

In PHP: addition is +, subtraction is -, multiplication is *, division is /, and modulo (remainder of division) is %. For increment use ++, for decrement use --, and it's generally good practice to use the prefix form. String concatenation uses ., and compound assignment operators include +=, -=, *=, /=, %=, and .=.

<?php
echo 1 + 2; // Outputs the result of '1 + 2'.
echo 3 - 2; // Outputs the result of '3 - 2'.
echo 3 * 2; // Outputs the result of '3 * 2'.
echo 6 / 2; // Outputs the result of '6 / 2'.
echo 6 % 5; // Outputs the remainder of '6 / 5'.

$test = 1 + 2; // The result of '1 + 2', which is 3, is assigned to variable 'test'.

$x = 0;
++$x; // This is the same as writing '$x = $x + 1'.

$y = 1;
--$y; // This is the same as writing '$y = $y - 1'.

$num1 = 10; // Assigns the number 10 to variable 'num1'.
$num1 += 2; // This is the same as writing '$num1 = $num1 + 2;'.
echo $num1; // Outputs the number 12.

$num2 = 10; // Assigns the number 10 to variable 'num2'.
$num2 -= 2; // This is the same as writing '$num2 = $num2 - 2;'.
echo $num2; // Outputs the number 8.

$num3 = 10; // Assigns the number 10 to variable 'num3'.
$num3 *= 2; // This is the same as writing '$num3 = $num3 * 2;'.
echo $num3; // Outputs the number 20.

$num4 = 10; // Assigns the number 10 to variable 'num4'.
$num4 /= 2; // This is the same as writing '$num4 = $num4 / 2;'.
echo $num4; // Outputs the number 5.

$num5 = 10; // Assigns the number 10 to variable 'num5'.
$num5 %= 3; // This is the same as writing '$num5 = $num5 % 3;'.
echo $num5; // Outputs the number 1.

$txt = 'Hello'; // Assigns the string 'Hello' to variable 'txt'.
$txt .= ' world'; // This is the same as writing '$txt = $txt . \' world\';'.
echo $txt; // Outputs the string 'Hello world'.

For more details, see this article.

Arrays (Indexed Arrays)

In PHP, you can define an array using array(). Since PHP 5.4, you can also use []. To inspect the full contents of an array, use var_dump().

<?php
$arr = array('miku', 'IA');

var_dump($arr);
echo $arr[0];

For more details, see this article.

Adding to Arrays and Things to Watch Out For

To add an element to an array, use []. To add multiple elements at once, array_push() is handy. In PHP, indexed arrays and associative arrays are treated the same internally, which means you can skip index numbers entirely. Also, note that even a string index that looks like a number will be treated as a numeric index — so watch out for that. To get the number of elements in an array, use count().

$arr = array('miku', 'IA');
$arr[] = 'rin';

var_dump($arr);
<?php
$arr = array('miku', 'IA');
array_push($arr, 'rin', 'ren');

var_dump($arr);
<?php
$arr = ['miku']; // Creates array 'arr' and assigns the string 'miku' to index 0.
$arr['0'] = 'IA'; // Assigns the string 'IA' to the element at string index '0' of array 'arr'.

echo $arr[0]; // This outputs 'IA'.
<?php
$vocaloids = [];
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';

echo count($vocaloids); // Gets the number of elements in array 'vocaloids' with 'count()' and outputs it with 'echo'.

For more details, see this article.

Functions and Arguments

Here's how you define a function and its arguments in PHP.

function function_name(arg1, arg2, arg3){
    // Write your process here.
}

To call a defined function, write the following.

function_name(argument);
<?php
// $width is the base and $height is the height.
function area_of_triangle($width, $height){
    $area = ($width * $height) / 2;

    echo 'A triangle with base ' . $width . ' and height ' . $height . ' has an area of ' . $area . '.';
}

area_of_triangle(10, 5);

For more details, see this article.

Associative Arrays

An associative array is an array where elements are managed by custom string keys rather than sequential numbers. Internally, PHP treats indexed arrays and associative arrays the same way. In PHP arrays of all kinds, the order of elements is always guaranteed.

<?php
$vocaloids = [];
$vocaloids['miku'] = '080-xxxx-1234';
$vocaloids['IA'] = '090-yyyy-1234';
$vocaloids['rin']  = '080-zzzz-1234';

For more details, see this article.

The Double Arrow Operator and Multidimensional Arrays

Using the double arrow operator => lets you create associative arrays with array(). Since PHP 5.4, [] works too. PHP also supports multidimensional arrays, though the syntax can get complex — watch out for missing commas and similar typos.

<?php
$vocaloids = array('miku' => '080-xxxx-1234');
// This is the same as writing '$vocaloids['miku'] = '080-xxxx-1234''.
<?php
$vocaloids = ['miku' => '080-xxxx-1234']; // Since PHP 5.4, you can use '[]' as well.
<?php
$MGS5TPP = array(
    'Title' => 'METAL GEAR SOLID V: The Phantom Pain',
    'Developer(s)' => 'Kojima Productions',
    'Producer' => 'Hideo Kojima',
    'Main Characters' => [
        'BIG BOSS',
        'Kazuhira Mirrer',
        'Revolver Ocelot',
        'Quiet',
        'Skull Face'
    ]
);

$MGS5TPP['Main Characters'][0] = 'Naked Snake'; // Replaces the string 'BIG BOSS' with the string 'Naked Snake'.

echo $MGS5TPP['Main Characters'][0]; // Outputs the string 'Naked Snake'.

For more details, see this article.

Boolean Values and Comparison Operators

A boolean value is either true or false. Comparison operators let you compare operands. Here are the commonly used comparison types in PHP.

1st Operand2nd OperandComparison Method
NumberNumberNumeric comparison
Numeric stringNumeric stringNumeric comparison
Numeric stringNumberNumeric comparison
Regular stringNumberNumeric comparison
Numeric stringRegular stringLexicographic comparison
Regular stringRegular stringLexicographic comparison

For more details, see this article.

if Statements

The if statement lets you branch execution based on a condition. If you include an else clause, it must always come last.

<?php
if(false){
    var_dump('Executed!');
}
else if(false){
    var_dump('Executed! (2)');
}
else{
    var_dump('Executed! (3)');
}

The following values are treated as 'false' in PHP.

  • The boolean false
  • The number 0
  • The floating-point number 0.0
  • An empty string ('' or "") and the string 0
  • An empty array (or associative array)
  • NULL

For more details, see this article.

Logical Operators

&& is the logical AND operator — the entire expression evaluates to true only when both operands are true. || is the logical OR operator — the entire expression evaluates to true when at least one operand is true. xor is the exclusive OR operator — the entire expression evaluates to true only when exactly one operand is true. ! is the logical NOT operator — it evaluates the operand as a boolean and then flips it.

<?php
if(true && true){
    var_dump('Executed!');
}
<?php
if(true || false){
    var_dump('Executed!');
}
<?php
if(true xor false){
    var_dump('Executed!');
}
<?php
if(!false){
    var_dump('Executed!');
}

For more details, see this article.

switch Statements

A switch statement lets you handle many branches at once. Without a break statement, execution falls through to the next case, so be careful. One thing to note about PHP's switch statement is that it doesn't do strict comparison — which is why many developers prefer to use if statements instead.

<?php
$num = 1;

switch($num){
    case 1:
        var_dump('It\'s 1!');
        break;
    case 2:
        var_dump('It\'s 2!');
        break;
    case 3:
        var_dump('It\'s 3!');
        break;
    default:
        var_dump('Default!');
        break;
}

If you want strict comparison inside a switch statement, here's the pattern to use.

<?php
$num = 1;

switch(true){
    case $num === 0:
        var_dump('It\'s 0!');
        break;
    case $num === 1:
        var_dump('It\'s 1!');
        break;
    case $num === 2:
        var_dump('It\'s 2!');
        break;
    default:
        var_dump('Default!');
        break;
}

For more details, see this article.

for Loops

The for loop lets you repeat a block of code, and is commonly used together with indexed arrays. Try to keep the update expression and condition expression as lightweight as possible.

<?php
$vocaloids = [];
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';

$cnt = count($vocaloids) - 1; // Subtracts 1 from the value returned by 'count()' and stores it in variable 'cnt'.
for($i = 0; $i <= $cnt; ++$i){ // Using '$i <= $cnt' as the condition keeps the loop condition lightweight.
    echo $vocaloids[$i] . "\n";
}

For more details, see this article.

do/while Loops

The while loop is another way to repeat code, just like the for loop. It's simpler to set up than a for loop, but that also makes it easier to accidentally create an infinite loop — so be careful.

<?php
$num = 0;

while($num < 10){
    var_dump($num);
    ++$num;
}

If you want to guarantee the loop body runs at least once regardless of the condition, use a do/while loop.

<?php
$num = 0;

do{
    var_dump($num);
    ++$num;
}while(false);

For more details, see this article.

foreach Loops

The foreach loop iterates over each element of an array. When you only need the values, write it like this.

<?php
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';

foreach($vocaloids as $val){
    echo $val;
}

When you need both the key (index) and the value, write it like this.

<?php
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';

foreach($vocaloids as $key => $val){
    echo 'Key \'' . $key . '\' of array \'vocaloids\' is \'' . $val . "\'.\n";
}

For more details, see this article.

And that wraps up the PHP Beginner series.

Thank you so much for reading all the way to the end. Hopefully the content here has added something useful to your knowledge. Take care, and hope to see you around!

This article was written by Sakurama.

Author's beloved small mammal

桜舞 春人 Sakurama Haruto

A Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him.

If you find any errors or copyright issues, please .