PHPDownload

Learn PHP step by step

Work through the modules in order or start with a topic you need. Each lesson includes a worked example and a change you can test.

Download PHP exercises (.zip)

Getting started

  1. Read a first PHP expression

    Print the number of lessons left in a short course. Printing an expression lets you see what PHP calculated before you build a page around it.

  2. Store a value and inspect its type

    A value arriving from an HTML form usually begins life as a string. The shape of its printed output can hide that distinction.

  3. Build a list of PHP modules

    A list keeps items in their insertion order. Use a list when position matters and you do not need to give each value a separate key.

  4. Read an associative array safely

    A settings array gives each value a meaningful key. Optional keys need an explicit fallback when you read them.

  5. Walk a nested collection

    A list of associative arrays can represent the rows of a small catalog. Each row can use the same keys while holding different values.

  6. Normalize a short search query

    Text entered into a search field often begins or ends with spaces. Trim it before comparing or storing it.

  7. Count pages with a for loop

    A for loop works well when both the first page and the last page are known.

  8. Process a queue until it is empty

    A worker often repeats a step until it has no remaining work. Start with a small list so you can inspect each transition.

  9. Write a typed helper function

    A capacity calculation is easier to reuse when you give it a name, parameter types and a clearly defined return type.

  10. Represent a catalog entry with an object

    A class can keep a short title and the behavior that presents it together. Create independent instances when two entries have different values.

  11. Handle a bad value with an exception

    A function with a clear input contract can tell its caller when a value falls outside that contract.

  12. Choose a label with a match expression

    Map a small set of known values to labels. A match expression compares values strictly and produces a single result.

  13. Read JSON and handle invalid input

    JSON separates an interchange format from the PHP arrays you use inside your program. Decide how you want malformed input to behave.

  14. Find the local date for an event

    An instant has a different calendar date depending on the timezone used to display it. Keep the instant and the display zone separate.

  15. Use a namespace for small PHP components

    Two libraries can choose the same short class name. A namespace makes the complete name unambiguous.

  16. Keep presentation separate from conversion

    An object that always creates its own formatter ties its results to one formatting choice. Inject a callable to choose that behavior at the boundary.

  17. Generate a command-line status line

    A command-line script can take an optional argument and still provide a useful default. The first element of argv is the script name.

  18. Count repeated labels in an array

    A frequency table accumulates a count for each distinct label. Read the current count and add one as each label arrives.

Language fundamentals

  1. Putting values on the page

    A PHP statement ends at the semicolon, not at the end of a line. This receipt combines three pieces of output without first building an intermediate string.

  2. Keep local and outer variables separate

    A function can use a name that also appears outside it. Each parameter belongs to the current call and changing it usually leaves the caller's variable alone.

  3. Convert a validated field into an integer

    An HTML form can send a number as text. Validate the value before turning it into a quantity so that an empty or inappropriate field does not silently become zero.

  4. Slice a predictable reference code

    A fixed-format ASCII identifier can be split by position. Work out which characters represent the series and which represent the issue before using substring offsets.

  5. Decide when a string needs escaping

    Single and double quotes give string literals different rules. To display punctuation in a code-generated label, distinguish the source-code character from the character that the visitor should see.

  6. Round a page estimate upward

    A list with a partial final page still needs a page for those remaining entries. Calculate the quotient first, then choose a rounding rule based on what the result represents.

  7. Give a configuration limit one name

    A named constant is suitable for a value that should remain the same during a request. Using one name for the page size prevents the limit and the display calculation from drifting apart.

  8. Choose the most specific condition first

    Order matters when more than one comparison can match the same input. A badge for completed work should take priority over the broader condition for work in progress.

  9. Group several states in a switch

    A switch can route two different status labels into the same display action. Put the shared behavior after both labels so that the choice is deliberately visible.

  10. Skip blank labels and stop after a limit

    A loop may need to discard unsuitable records but still keep searching. Skipping the current row and ending the whole scan are separate decisions.

  11. Make one pass before testing a condition

    A do-while loop is useful when the first operation must happen even when no further work is expected. A regular while loop checks its condition before the first operation.

  12. Edit a list while preserving meaningful keys

    PHP arrays can mix insertion order with numeric indexes. Removing a record can leave a gap. Decide whether later consumers expect the old keys or a fresh list.

  13. Sort counts without losing their labels

    If a category name is stored as the array key, a sort that discards keys can separate each count from the label it describes. Choose a sorting operation that preserves that association.

  14. Transform a list with a callback

    A callback lets an array operation ask your function to process each element. Keep the callback focused on one value and return a result instead of printing inside it.

  15. Match a complete input format

    When a ticket reference must look like two uppercase letters followed by four digits, check the whole field. Finding a matching substring inside a longer string answers a different question.

Web applications and objects

  1. Read parameters from the intended input channel

    A PHP page can receive a query string, form body and cookies in a single request. Read from the channel that matches the purpose of the field so precedence stays explicit.

  2. Return useful errors for form fields

    A form handler needs to explain which fields need attention. Collect per-field errors before deciding whether to save the submission.

  3. Render user text in an HTML template

    Plain-text data can contain characters that have special meaning in HTML. Encode the value for the place where the template will display it.

  4. Summarize a text file using a stream

    Streams provide a common way to read data from files and other sources. The temporary stream in this exercise behaves like a file while keeping the lesson self-contained.

  5. Read CSV rows with quoted punctuation

    CSV fields can contain commas and doubled quotes. Splitting every line on a comma can separate one title into multiple fields.

  6. Distinguish an absent upload from a completed one

    An upload handler receives a status code before it decides whether a temporary file is usable. A missing file, a successful transfer and a transfer error are different states.

  7. Keep a preference separate from session state

    A visitor preference can be remembered in a cookie, while a session associates server-side data with a request. Treat a preference arriving from a browser as input and check it against the options your program supports.

  8. Separate a public action from an object's private state

    A public method can enforce rules about how private data changes. Clients can ask the object to perform a meaningful operation without manipulating its storage directly.

  9. Pass an interface into a report generator

    An interface describes an operation that different classes can supply. Type the report function against the shared contract so it can use another implementation later.

  10. Share a method with a trait

    Two unrelated classes may need the same small behavior. A trait can supply a method to both classes without forcing either class into a common inheritance hierarchy.

  11. Use a named factory to build a value

    A static factory method can explain the representation it accepts. A class constant can name an internal conversion factor shared by every instance.

  12. Iterate over a generated sequence

    A generator yields one value at a time. The consuming code can accept an iterable without needing the entire sequence in an array.

  13. Choose between byte and character counts

    A UTF-8 string stores some characters in several bytes. A storage limit, visible label limit and cursor position may each use a different unit.

  14. Test one calculation against boundary cases

    A small deterministic function can be checked by writing down inputs and expected outputs. Include the boundary where a new page starts rather than testing only a comfortable middle value.

Data, integration and operations

  1. Connect PDO and check the database driver

    A database connection begins with a driver name and connection details. This lesson opens a temporary SQLite database in memory so that each run starts with the same empty state.

  2. Insert a record and capture the generated identifier

    A table can give every record an identifier, even when two rows share the same title. Let the database generate the ID and read it back on the same connection.

  3. Run a related set of writes in one transaction

    A batch of related changes should either commit together or leave the database in its earlier state. A unique constraint gives the example a predictable way to encounter a failed insert.

  4. Filter and order the rows for a small results page

    An explicit filter determines which records qualify. An explicit ordering determines which qualifying record appears first. Both are necessary for a reproducible short results page.

  5. Modify a row selected by its stable ID

    A title may change, and two rows can share the same visible name. Use a stable key to choose the row for an update or removal.

  6. Read records from a known XML format

    An XML element may have attributes as well as child elements. Decide which represents the stable key and which contains text for display.

  7. Create XML using document nodes

    When text contains an ampersand, handcrafted XML can be hard to get right. Document nodes keep element names and values separate from the serialized output.

  8. Design a small JSON response for live search

    A search endpoint can accept a short term and return a list of matches. Keeping its response shape consistent allows the browser to show empty results without a separate parsing rule.

  9. Check dependency requirements before running a project

    Project metadata can distinguish the PHP runtime requirement from library dependencies. Read that metadata before installing a program on a shared host.

  10. Read command-line arguments with defaults

    A PHP script launched from the command line receives its own filename as its first argument. The first user-provided value comes next.

  11. Decide what a log entry needs to explain

    A background job can fail when the visitor is no longer present. A structured log record connects the event, the relevant job and the outcome so an operator can follow up.

  12. Verify a stored password without revealing it

    An account should store a password hash produced by the password API. During sign-in compare the user's input against that stored hash.

Inquiry list