PHP how-to
Short ready-made solutions to common PHP tasks with code examples.
Strings
- How to add leading zeros to a numberLeading zeros in PHP: str_pad and sprintf for order numbers, times and dates.
- How to capitalize the first letter of a stringCapitalizing the first letter in PHP: ucfirst, mb_ucfirst and an approach for versions before PHP 8.4.
- How to check if a string contains a substringChecking for a substring in PHP: str_contains, case-insensitive search and finding the position.
- How to check if a string is a palindromeChecking for a palindrome in PHP: comparing with the reversed string, ignoring case, spaces and punctuation.
- How to check if a string is emptyChecking for an empty string in PHP: comparing with an empty string, whitespace and the empty() trap.
- How to check that a string holds a numberChecking for a number in a string in PHP: is_numeric, digits only with ctype_digit and an integer with filter_var.
- How to check what a string ends withChecking the ending of a string in PHP: str_ends_with, ignoring case and several options.
- How to check what a string starts withChecking the beginning and the end of a string in PHP: str_starts_with and str_ends_with.
- How to compare strings ignoring caseComparing strings ignoring case in PHP: converting to one case and strcasecmp.
- How to convert a string to an arraySplitting a string into an array in PHP: by a separator, by characters and by words.
- How to convert a string to uppercase or lowercaseChanging the case of a string in PHP: mb_strtoupper and mb_strtolower for any alphabet, a capital first letter.
- How to convert camelCase to snake_case and backConverting names in PHP: from camelCase to snake_case with preg_replace and back with ucwords.
- How to count the characters in a stringThe length of a string in PHP: mb_strlen for characters, strlen for bytes and counting occurrences of a character.
- How to count words in a stringCounting words in PHP: str_word_count for English text and an approach for any language.
- How to extract numbers from a stringExtracting numbers from text in PHP: every number with preg_match_all, digits only and the first number.
- How to find the position of a substringFinding a position in a string in PHP: strpos, comparing with false, the last occurrence and all occurrences.
- How to generate a random passwordGenerating a password in PHP: random characters with random_int and a password with required digits.
- How to generate a random stringA random string in PHP: a token with random_bytes, a string from your own character set and a confirmation code.
- How to generate a UUIDGenerating a version 4 UUID in PHP from random bytes and checking the format with a regular expression.
- How to get the domain from an email address or a linkExtracting a domain in PHP: parse_url for a link and splitting an email address at the @ sign.
- How to mask part of a string with asterisksMasking data in PHP: a card number, a phone and an email address with asterisks in place of some characters.
- How to parse and build a query stringURL parameters in PHP: parse_str turns a query string into an array, http_build_query turns an array into a string.
- How to remove all whitespace from a stringRemoving whitespace in PHP: str_replace for plain spaces, preg_replace for any whitespace and collapsing repeats.
- How to remove HTML tags from a stringRemoving tags in PHP: strip_tags, allowed tags and the difference from escaping.
- How to remove the last character from a stringRemoving the last character of a string in PHP with mb_substr and rtrim, including non-ASCII text.
- How to replace text in a stringReplacing a substring in PHP: str_replace, several replacements in one call and case-insensitive replacement.
- How to reverse a stringReversing a string in PHP: strrev for ASCII and an approach that works with any alphabet.
- How to show line breaks on a pageLine breaks in HTML with PHP: nl2br together with htmlspecialchars and splitting text into paragraphs.
- How to trim whitespace from a stringRemoving whitespace in PHP: trim, ltrim, rtrim and collapsing repeated spaces inside a string.
- How to truncate a string to a given lengthTruncating a long string in PHP and adding an ellipsis: mb_substr and mb_strimwidth.
- How to turn a string into a URL slugA slug in PHP: lowercase, hyphens instead of spaces and removing extra characters.
- How to validate an email addressValidating an email in PHP with filter_var and preparing the address before saving.
Arrays
- How to check if a key exists in an arrayChecking an array key in PHP: isset, array_key_exists and a default value with ??.
- How to check if a value exists in an arrayChecking for a value and a key in a PHP array: in_array, array_key_exists, isset and array_search.
- How to check if an array is emptyChecking for an empty array in PHP: comparing with [], count and empty.
- How to check that every array element satisfies a conditionChecking all or at least one array element in PHP: array_all and array_any, a variant for older versions.
- How to check whether an array is associative or a listA list or an associative array in PHP: the array_is_list function and its behaviour after removing elements.
- How to compare two arraysComparing arrays in PHP: the == and === operators, differing and common elements with array_diff and array_intersect.
- How to convert an array to a stringConverting an array to a string in PHP: implode, key-value pairs and JSON.
- How to convert an object to an arrayAn object to an array in PHP: get_object_vars, a type cast and nested objects through JSON.
- How to count occurrences of a value in an arrayCounting repetitions in a PHP array: array_count_values, a single value and counting by a condition.
- How to filter an arrayFiltering an array in PHP with array_filter: by a condition, removing empty values, filtering by key.
- How to find an array element by a conditionFinding an element in an array of arrays in PHP: array_find, a version for older releases and searching by a field value.
- How to find duplicate values in an arrayFinding duplicates in PHP: array_count_values and array_filter, checking whether repeats exist.
- How to find the average of an arrayThe arithmetic mean in PHP: array_sum and count, guarding against an empty array and the average of a field.
- How to find the maximum and minimum in an arrayThe largest and smallest value of an array in PHP: max, min and finding the key of the maximum.
- How to find the median of an arrayThe median in PHP: sorting and the middle element, the case of an even count.
- How to flatten a nested arrayTurning a nested array into a flat one in PHP: array_merge with unpacking and a recursive version.
- How to get a random array elementA random array element in PHP: array_rand, several elements and a secure pick with random_int.
- How to get one field's values from an array of arraysA column from an array of arrays in PHP: array_column, values with keys and summing a field.
- How to get the first and last element of an arrayThe first and last element of an array in PHP: by index and with array_key_first and array_key_last.
- How to group an array by a field valueGrouping an array of arrays by a field in PHP: an accumulating loop and counting per group.
- How to insert an element into the middle of an arrayInserting into a PHP array by position: array_splice with zero length, several elements and inserting at the start.
- How to loop through an array with an indexLooping through an array in PHP with access to the index or key using foreach.
- How to merge two arraysMerging arrays in PHP with array_merge, the spread operator and the + operator.
- How to paginate an arrayPaginating an array in PHP: array_slice with an offset and calculating the number of pages.
- How to remove an element from an arrayRemoving an array element in PHP: by key, by value, the first and the last.
- How to remove duplicates from an arrayRemoving repeated values from an array in PHP with array_unique and array_values.
- How to remove duplicates from an array of arrays by a fieldUnique records in PHP by one field: array_column with an index and keeping the first record.
- How to remove empty values from an arrayRemoving empty array elements in PHP: array_filter without a function, keeping zero and renumbering.
- How to reverse an arrayReversing the order of elements in PHP: array_reverse, preserving keys and the difference from sorting.
- How to shuffle an arrayA random order of elements in PHP: shuffle, preserving keys and several random elements.
- How to sort an arraySorting an array in PHP: ascending, descending, by a field and with keys preserved.
- How to sort an array by keysSorting by keys in PHP: ksort, krsort for the reverse order and uksort with your own function.
- How to sort an array of arrays by a fieldSorting an array of arrays in PHP: usort and the <=> operator, descending and by several fields.
- How to split an array into chunksSplitting an array into chunks in PHP: array_chunk, pages with array_slice and the number of pages.
- How to sum the values of an arraySum and average of an array in PHP: array_sum, count and summing a field with array_column.
- How to swap the values of two variablesSwapping variable values in PHP in one line with array destructuring.
Numbers
- How to calculate a factorialA factorial in PHP: array_product and range, a loop and the integer limit.
- How to calculate a percentagePercentages in PHP: a percentage of a number, one number as a share of another and a percentage change.
- How to check if a number is evenChecking parity and divisibility of a number in PHP with the remainder operator.
- How to check whether a number is primeA prime number in PHP: checking divisors up to the square root and a list of primes.
- How to clamp a number to a rangeLimiting a number from above and below in PHP with min and max.
- How to convert a number to binary or hexadecimalNumber bases in PHP: decbin and dechex, the reverse conversion and base_convert for any base.
- How to convert a string to a numberConverting a string to a number in PHP: the (int) and (float) casts and checking with is_numeric.
- How to find the sum of a number's digitsThe sum of digits in PHP: through a string and array_sum or through division with a remainder.
- How to format a number with thousands separatorsFormatting numbers in PHP with number_format: thousands separators and decimal places.
- How to format a pricePrinting a price in PHP: number_format with cents and a thousands separator, a price from cents.
- How to generate a random numberA random number, a random array element and shuffling an array in PHP.
- How to generate Fibonacci numbersThe Fibonacci sequence in PHP: a loop with two variables and a generator.
- How to round a number to two decimal placesRounding a number to two decimal places in PHP: round, number_format, rounding down and up.
- How to show a file size in a readable formBytes to kilobytes and megabytes in PHP: a size formatting function.
Date and time
- How to add days to a dateDate arithmetic in PHP: modify on DateTimeImmutable, months and working days.
- How to calculate age from a birth dateAge from a birth date in PHP using the diff method.
- How to check whether a date is a weekendA weekend day in PHP: the day-of-week number in the N format and finding the next working day.
- How to check whether a year is a leap yearA leap year in PHP: the L character in a date format, a check with checkdate and the division rule.
- How to compare two datesComparing dates in PHP: operators on DateTimeImmutable objects and strings in the YYYY-MM-DD format.
- How to convert a time to another time zoneTime zones in PHP: DateTimeZone and the setTimezone method, storing time in UTC.
- How to convert a timestamp to a date and backA Unix timestamp in PHP: date and DateTimeImmutable for output, strtotime and getTimestamp for the reverse conversion.
- How to find the difference between two datesThe difference between dates in PHP: number of days, years and months with DateTime::diff, adding days.
- How to format a dateFormatting a date in PHP: the date function, the DateTime class and the main format characters.
- How to get the current date and timeThe current date in PHP: the date function, the DateTimeImmutable object and the time zone.
- How to get the day of the weekThe day of the week for a date in PHP: the number, the English name and a localised name.
- How to get the first and last day of a monthThe bounds of a month in PHP: the first day of and last day of expressions, the number of days in a month.
- How to measure the execution time of codeTiming code in PHP: hrtime for precise measurements, microtime and comparing two approaches.
- How to show "5 minutes ago"Relative time in PHP: the difference in seconds and picking a suitable unit — minutes, hours, days.
- How to validate a dateValidating a date in PHP: createFromFormat with a round-trip check, and checkdate.
Files
- How to append a line to a fileAppending to a file in PHP: the FILE_APPEND flag, the LOCK_EX lock and the a mode of fopen.
- How to check whether a file existsChecking a file in PHP: is_file, the difference from file_exists and checking read access.
- How to copy or move a fileCopying and moving files in PHP: the copy and rename functions, checking the result.
- How to create a directoryCreating a directory in PHP: mkdir with nested folders and checking existence with is_dir.
- How to delete a fileDeleting a file in PHP: unlink with an existence check, and removing a folder with its content.
- How to get a file extensionA file extension in PHP: pathinfo, lowercase and the name without the extension.
- How to get the size of a fileThe size of a file in PHP: filesize and converting bytes to kilobytes and megabytes.
- How to list the files in a folderListing a folder's files in PHP: scandir, and only the needed extensions with glob.
- How to read a CSV fileReading CSV in PHP: fgetcsv, rows with headings as associative arrays.
- How to read a fileReading a file in PHP: all at once, line by line into an array and row by row for large files.
- How to read a file line by lineReading a file line by line in PHP: the file function for small files, fgets and a generator for large ones.
- How to read and write a JSON fileA JSON file in PHP: file_get_contents with json_decode, writing with json_encode and readable formatting.
- How to send a file as a downloadDownloading a file in PHP: the Content-Disposition and Content-Length headers, output with readfile and protecting the path.
- How to upload a file to the serverUploading a file in PHP: a form with enctype, checking the error, size and extension, saving with move_uploaded_file.
- How to write a message to a log fileYour own log in PHP: file_put_contents with a date and the FILE_APPEND flag, the error_log function and the Monolog library.
- How to write data to a CSV fileWriting CSV in PHP: fputcsv for every row, headers from array keys and opening the file in Excel.
- How to write data to a fileWriting to a file in PHP: file_put_contents, appending and creating the folder.
Forms and web
- How to allow requests from another site (CORS)CORS headers in PHP: Access-Control-Allow-Origin for your own sites and answering the OPTIONS preflight request.
- How to check password strengthChecking a password in PHP: a minimum length, letters and digits present, a list of clear error messages.
- How to check the request methodThe HTTP request method in PHP: REQUEST_METHOD, handling a form and a 405 response for the wrong method.
- How to get form dataForm data in PHP: the $_POST and $_GET arrays, a default value and validation.
- How to get the current page addressThe current URL in PHP: REQUEST_URI, the full address from $_SERVER parts and the path without parameters.
- How to get the visitor's IP addressThe IP address in PHP: REMOTE_ADDR, the X-Forwarded-For header behind a proxy and validating the address.
- How to keep data in the sessionThe session in PHP: session_start, writing and reading $_SESSION, removing a value and ending the session.
- How to print user text safelyProtecting against XSS in PHP: htmlspecialchars on output, line breaks and printing into an attribute.
- How to protect a form with a CSRF tokenCSRF protection in PHP: a random token in the session, a hidden form field and comparing with hash_equals.
- How to read JSON from the request bodyJSON in a request in PHP: reading php://input, parsing with error checks and a JSON response.
- How to redirect to another pageRedirecting in PHP: the Location header, the response code and parameters in the address.
- How to return a 404 errorA 404 response in PHP: http_response_code, a custom error page and a JSON response for an API.
- How to send a JSON responseA JSON response in PHP: the Content-Type header, json_encode and a status code for errors.
- How to send an emailSending an email from PHP: the mail function and the PHPMailer library with SMTP.
- How to send an HTTP request to an APIAn HTTP request from PHP: file_get_contents for a simple GET and cURL for a JSON POST with headers and error checks.
- How to set and read a cookieCookies in PHP: setcookie with options, reading from $_COOKIE and removing.
- How to store and verify a passwordPasswords in PHP: password_hash on registration, password_verify on login and rehashing.
- How to validate a phone numberValidating a phone number in PHP: stripping extra characters, the length of the number and normalising.
- How to validate a URLValidating a URL in PHP: filter_var with FILTER_VALIDATE_URL and limiting the schemes to http and https.
JSON and databases
- How to check whether a row exists in a databaseChecking that a record exists in PHP with PDO: SELECT 1 with LIMIT and fetchColumn.
- How to connect to a databaseConnecting to a database in PHP through PDO: the connection string, the error mode and checking the connection.
- How to connect to MySQL with MySQLiA MySQLi connection in PHP: the mysqli object, the utf8mb4 charset and a prepared statement.
- How to convert an array to JSONAn array to JSON in PHP: json_encode, non-ASCII letters kept as is, indentation and error handling.
- How to count the rows in a tableCOUNT in PHP with PDO: fetchColumn for a single value, counting by a condition and by groups.
- How to delete a row from a databaseDELETE in PHP with PDO: a prepared statement, checking the result and soft deletion.
- How to get the id of an inserted rowThe identifier of a new record in PHP: the lastInsertId method after INSERT and related records.
- How to insert a row into a databaseInserting a row in PHP through PDO: a prepared statement, the new row's identifier and several rows.
- How to paginate database resultsPagination in PHP with PDO: LIMIT and OFFSET with bindValue and calculating the number of pages.
- How to parse a JSON stringJSON to an array in PHP: json_decode, error handling and reading JSON from a file.
- How to run several queries in a transactionA transaction in PHP with PDO: beginTransaction, commit and rollBack in a try block.
- How to search records by part of a stringA LIKE search in PHP with PDO: percent signs in the parameter value and escaping special characters.
- How to select rows from a databaseSelecting from a database in PHP through PDO: every row, a single row and a query with a parameter.
- How to update a row in a databaseUPDATE in PHP with PDO: a prepared statement, the number of changed rows and the danger of a query without WHERE.
Miscellaneous
- How to find out and check the PHP versionThe PHP version: the PHP_VERSION constant, comparing with version_compare and checking extensions.
- How to inspect the contents of a variableDebug output in PHP: var_dump with types, print_r for arrays and writing to the log without printing to the page.
- How to make a singletonThe singleton pattern in PHP: a private constructor and a static method, its drawbacks and a replacement.
- How to read an environment variableEnvironment variables in PHP: getenv with a default value and required variables.