Examples

PHP examples

Learn server-side web programming basics.

14 examples

PHP Basics

Print a value from a PHP script.

PHP

PHP Arrays

Loop through an indexed array.

PHP

PHP Functions

Declare typed parameters and return values.

PHP

PHP strings, sprintf, and regular expressions

Format text with sprintf, split and join strings, and match patterns with preg functions.

PHP

PHP strict types, match, and the nullsafe operator

Use union types, a match expression, constructor promotion, and ?-> to write safer code.

PHP

PHP closures, array functions, and generators

Transform arrays with map, filter, and reduce, capture variables in closures, and produce values lazily with yield.

PHP

PHP Classes

Hide a property and change it only through methods.

PHP

PHP interfaces, traits, and abstract classes

Share a contract with an interface, share code with a trait, and share both with an abstract base.

PHP

PHP Associative Arrays

Map names to values and loop over keys and values.

PHP

PHP sorting, usort, and the spaceship operator

Sort arrays by value or by custom rules, and combine several sort keys with <=>.

PHP

PHP SPL data structures: stack, queue, and heap

Use the standard SplStack, SplQueue, SplMinHeap, and SplPriorityQueue classes.

PHP

PHP unit tests with closures

Write a tiny test runner with named test closures and check normal values and expected errors.

PHP

PHP password_hash, password_verify, and hash_hmac

Store passwords with bcrypt through the built-in API and sign messages with HMAC.

PHP

PHP preventing XSS with htmlspecialchars

Encode user text before printing it into HTML, and escape for the right context.

PHP