1. What is PHP?
PHP is a server-side scripting language for web pages. The server runs the PHP code and sends HTML to the browser.
<?php
echo "Hello, World!";
?>
Full lesson: Php intro
59 questions about PHP with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.
PHP is a server-side scripting language for web pages. The server runs the PHP code and sends HTML to the browser.
<?php
echo "Hello, World!";
?>
Full lesson: Php intro
PHP code starts with <?php and ends with ?>. You can mix PHP code with HTML in one file.
<?php
echo "My first PHP script";
?>
Full lesson: Php syntax
Write a dollar sign, then the name, then the value in quotes. Use single or double quotes for text.
<?php
$name = "Anna";
echo $name;
?>
Full lesson: Php string
Put the condition in round brackets after if. Put each block in curly braces. The else block runs when the condition is false.
<?php
$age = 20;
if ($age >= 18) {
echo "Adult";
} else {
echo "Child";
}
?>
Full lesson: Php if else
The while loop runs its block while the condition is true. Change the counter inside the loop to stop it.
<?php
$i = 1;
while ($i <= 3) {
echo $i;
$i++;
}
?>
Full lesson: Php looping
Use the array() function or the short square bracket syntax. Each value gets a numeric key that starts at 0.
<?php
$colors = array("red", "green", "blue");
echo $colors[1];
?>
Full lesson: Php arrays
Call is_array() with the variable. The function returns TRUE for an array and FALSE for other types.
<?php
$arr = array("a", "b");
var_dump(is_array($arr));
?>
Full lesson: Php is array function
Call is_string() with the variable. The function returns TRUE when the value is a string.
<?php
var_dump(is_string("99"));
var_dump(is_string(123.05));
?>
Full lesson: Php is string function
Call is_object() with the variable. The function returns TRUE when the value is an object.
<?php
$obj = new stdClass;
var_dump(is_object($obj));
?>
Full lesson: Php is object function
Call gettype() with the variable. It returns a string such as integer, string, or array.
<?php
echo gettype(102);
echo gettype("text");
?>
Full lesson: Php gettype function
Call settype() with the variable and the new type name. The function changes the variable in place and returns TRUE on success.
<?php
$foo = "5bar";
settype($foo, "integer");
echo $foo;
?>
Full lesson: Php settype function
Call join() with a separator and the array. The function puts the separator between each element.
<?php
$arr = array('Hello','World!');
echo join(" ", $arr);
?>
Full lesson: Func string join
Call array_merge() with both arrays. If two elements share a key, the last value wins.
<?php
$a1 = array("a" => "red", "b" => "green");
$a2 = array("c" => "blue", "b" => "yellow");
print_r(array_merge($a1, $a2));
?>
Full lesson: Func array merge
Call array_diff() with the first array and the second array. The function returns the values that are only in the first array.
<?php
$a1 = array("red", "green", "blue");
$a2 = array("red", "green");
print_r(array_diff($a1, $a2));
?>
Full lesson: Func array diff
Use list() on the left side and the array on the right side. This works only for arrays with numeric keys.
<?php
$my_array = array("Dog","Cat","Horse");
list($a, $b, $c) = $my_array;
echo $a;
?>
Full lesson: Func array list
Call array_shift() with the array. The function removes the first element and returns its value.
<?php
$a = array("red", "green", "blue");
echo array_shift($a);
print_r($a);
?>
Full lesson: Func array shift
Call array_unshift() with the array and the new values. Numeric keys restart from 0 after the insert.
<?php
$a = array("red", "green");
array_unshift($a, "blue");
print_r($a);
?>
Full lesson: Func array unshift
Call array_udiff() with both arrays and your function name. Your function decides which values are equal.
<?php
function myfunction($a,$b) {
if ($a===$b) { return 0; }
return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green");
$a2=array("a"=>"blue","b"=>"black");
print_r(array_udiff($a1,$a2,"myfunction"));
?>
Full lesson: Func array udiff
Call filetype() with the path. It returns a word such as file or dir, or FALSE on failure.
<?php
echo filetype("test.txt");
?>
Full lesson: Func filesystem filetype
Call imagecolorsforindex() with the image and a color index. It returns an array with red, green, blue, and alpha keys.
<?php
$im = imagecreatefrompng('example-logo.png');
$color_index = imagecolorat($im, 40, 20);
print_r(imagecolorsforindex($im, $color_index));
?>
Full lesson: Php imagecolorsforindex
Call the query() method on the PDO object with your SQL string. The method returns a statement object for the result.
<?php
$pdo = new PDO('sqlite::memory:');
$stmt = $pdo->query('SELECT 1 AS n');
print_r($stmt->fetch());
?>
Full lesson: Pdo query
Call beginTransaction() before your queries. Then call commit() to save all changes at once.
<?php
$pdo->beginTransaction();
$pdo->exec("INSERT INTO users (name) VALUES ('Ann')");
$pdo->commit();
?>
Full lesson: Pdo commit
The returned string can change in future PHP versions. Use an is_* function such as is_array() instead.
<?php
if (is_array($data)) {
echo "This is an array";
}
?>
Full lesson: Php gettype function
The list() function works only for numerically indexed arrays. String keys do not fill the variables.
<?php
$my_array = array("a" => "Dog", "b" => "Cat");
list($x, $y) = $my_array;
var_dump($x);
?>
Full lesson: Func array list
When two arrays share a key, the last value overwrites the earlier value. Check your keys before you merge.
<?php
$a1 = array("b" => "green");
$a2 = array("b" => "yellow");
print_r(array_merge($a1, $a2));
?>
Full lesson: Func array merge
The function gives all numeric keys new numbers that start from 0. String keys stay the same.
<?php
$a = array(1, 2, 3);
array_shift($a);
print_r($a);
?>
Full lesson: Func array shift
The separator must come before the array. Put the arguments in the wrong order and the output is wrong.
<?php
$arr = array('Hello','World!');
echo join(" ", $arr);
?>
Full lesson: Func string join
The function caches its result. Call clearstatcache() after a file changes.
<?php
clearstatcache();
echo filetype("test.txt");
?>
Full lesson: Func filesystem filetype
The function needs a color index from imagecolorat(). Pass the pixel result directly to get the color array.
<?php
$im = imagecreatefrompng('example-logo.png');
$idx = imagecolorat($im, 40, 20);
print_r(imagecolorsforindex($im, $idx));
?>
Full lesson: Php imagecolorsforindex
You call fopen() with a file name and a mode. The mode sets read or write access. The function returns a file handle.
<?php
$file = fopen("welcome.txt", "r");
?>
Full lesson: Php file
You call get_resource_type() with a resource handle. The function returns a string that names the resource type. An invalid handle causes an error.
<?php
$fp = fopen("foo", "w");
echo get_resource_type($fp);
?>
Full lesson: Php get resource type function
You call getimagesizefromstring() with the image data. The function returns an array with size and type information. It works like getimagesize() but takes a string, not a file name.
<?php
$data = file_get_contents("example-logo.png");
$info = getimagesizefromstring($data);
print_r($info);
?>
Full lesson: Php getimagesizefromstring
You call imagearc() with the image, center point, size, angles, and color. The function draws the arc on the image. You need the GD library.
<?php
$im = imagecreatetruecolor(200, 200);
$white = imagecolorallocate($im, 255, 255, 255);
imagearc($im, 100, 100, 150, 100, 0, 360, $white);
?>
Full lesson: Php imagearc
You call die() with a message when an operation fails. The script stops and sends the message. This is a simple error handling method.
<?php
$file = fopen("welcome.txt", "r") or die("Cannot open file.");
?>
Full lesson: Php error
It imports GET, POST, and Cookie variables into the global scope. The function is no longer supported in recent PHP versions. Do not use it in new code.
<?php
import_request_variables("gp", "prefix_");
?>
Full lesson: Php import request variables function
The function is removed from recent PHP versions. Your code will fail on those versions. Use $_GET, $_POST, and $_COOKIE instead.
Full lesson: Php import request variables function
A closed resource is no longer a valid resource. The function raises an error for an invalid handle. Check the resource before you call the function.
Full lesson: Php get resource type function
The function expects image data in a string, not a file path. A file name string is not valid image data. The function fails and returns false.
Full lesson: Php getimagesizefromstring
The image functions need the GD extension. Without GD, the function is undefined. Your script stops with a fatal error.
Full lesson: Php imagearc
fopen() returns false when it cannot open the file. If you do not check the result, later file operations fail. Always test the handle before you use it.
Full lesson: Php file
A message helps you find the cause of the error. Without a message, the script stops with no clear reason. Add a short text to die().
Full lesson: Php error
The "w" mode clears the file contents. It also creates a new file if the file does not exist. Use "r" for read-only access.
Full lesson: Php file
The function needs a valid resource handle. A string or number is not a resource. The function raises an error for an invalid parameter.
Full lesson: Php get resource type function
File operations can fail for many reasons, such as a missing file. Without error checks, the script continues with bad data. Add checks after each file call.
Full lesson: Php error
PHP code runs on the server. The server sends only the plain result to the browser.
<?php echo "Hello, PHP!"; ?>
Full lesson: Php intro
The default file extension is .php. A web server parses this file for PHP code.
Full lesson: Php syntax
Use an array. An array holds many values in one variable.
$cars = array("Volvo", "BMW", "Toyota");
Full lesson: Php arrays
The three types are numeric, associative, and multidimensional. A numeric array uses number keys. An associative array uses named keys.
Full lesson: Func array
Use the key in square brackets. The first item has key 0.
$cars = array("Volvo", "BMW"); echo $cars[0];
Full lesson: Php arrays
Install a web server, PHP, and a database. The official PHP site gives the steps.
Full lesson: Php install
The array() function creates an array. You can give values or key and value pairs.
$a = array("name" => "Tom", "age" => 20);
Full lesson: Func array
Open the file with fopen() in read mode. Then read the data with a read function.
$f = fopen("test.txt", "r"); $data = fread($f, filesize("test.txt")); fclose($f);
Full lesson: Php file
Call beginTransaction() on the PDO object. This turns off auto-commit for the next statements.
$dbh->beginTransaction();
Full lesson: Pdo commit
Use imagearc() on an image resource. Give the center, width, height, start angle, end angle, and color.
$img = imagecreatetruecolor(200, 200); $white = imagecolorallocate($img, 255, 255, 255); imagearc($img, 100, 100, 150, 150, 0, 180, $white);
Full lesson: Php imagearc
array_merge() renumbers numeric keys. The old number keys do not stay. Use the + operator to keep keys.
$a = array(5 => "x"); $b = array(5 => "y"); print_r($a + $b);
Full lesson: Func array merge
array_unshift() gives new number keys to all items. The old keys are lost. Use string keys if you need stable keys.
$a = array(1 => "a", 2 => "b"); array_unshift($a, "z"); print_r($a);
Full lesson: Func array unshift
settype() changes the variable in place. The old array data is gone. Make a copy first if you need both.
$a = array(1, 2); settype($a, "string"); echo $a;
Full lesson: Php settype function
commit() needs an open transaction. Without one, the call fails and returns false. Always start the transaction first.
$dbh->beginTransaction(); $dbh->commit();
Full lesson: Pdo commit
imagecolorsforindex() works on palette images only. A truecolor image has no color index. Use imagecolorat() to read a truecolor pixel.
$rgb = imagecolorat($img, 10, 10); $c = imagecolorsforindex($img, $rgb);
Full lesson: Php imagecolorsforindex