PHP Cheat Sheet, Cheat Sheet of Computer Science

PHP in discussion about arrays, strings, operators and filters and HTTP functions in php.

Typology: Cheat Sheet

2021/2022

Uploaded on 07/05/2022

carol_78
carol_78 🇦🇺

4.8

(59)

1K documents

1 / 38

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Beginner’s essential
PHP Cheat Sheet
Fast, flexible and pragmatic scripting language.
#################
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26

Partial preview of the text

Download PHP Cheat Sheet and more Cheat Sheet Computer Science in PDF only on Docsity!

Beginner’s essential

PHP Cheat Sheet

Fast, flexible and pragmatic scripting language.

#################

TABLE OF CONTENTS

  • PHP Basics
  • Variables and Constants
  • PHP Arrays – Grouped Values
  • PHP Strings
  • PHP Operators
  • Loops in PHP
  • Conditional Statements
  • Working with Forms in PHP
  • PHP Filters
  • HTTP Functions in PHP
  • Working with MySQL
  • Date and Time
  • PHP Errors

Types of Data

Integers Integers are non-decimal numbers between -2,147,483,648 and , 147,483,647. They must have at least one digit and no decimal point. Can be in decimal, hexadecimal or octal.

Floats This is the name for numbers with a decimal point or in exponential form.

Strings This simply means text, we will talk about it in detail further below.

Boolean values Meaning true/false statements.

Arrays Arrays are variables that store several values. We will talk about them in detail further below.

Objects Objects store both data and information on how to process it.

Resources These are references to functions and resources outside of PHP.

NULL A variable that is NULL doesn’t have any value.

Variable Scope

function myFunction() {

global $a, $b;

$b = $a - $b;

}

Predefined Variables

$GLOBALS

Used to access global variables from anywhere inside a PHP script

$_SERVER

Contains information about the locations of headers, paths and scripts

$_GET Can collect data that was sent in the URL or submitted in an HTML form

$_POST Used to gather data from an HTML form and to pass variables

$_REQUEST Also collects data after submitting an HTML form

Variable-handling Functions

boolval Used to retrieve the boolean value of a variable

debug_zval_dump Outputs a string representation of an internal zend value

empty Checks whether a variable is empty or not

floatval Get the float value of a variable (doubleval is another possibility)

get_defined_vars Returns an array of all defined variables

get_resource_type Returns the resource type

gettype Retrieves the variable type

import_request_variables Import GET/POST/Cookie variables into the global scope

intval Find the integer value of a variable

is_array Checks whether a variable is an array

is_bool Finds out if a variable is a boolean

unserialize Creates a PHP value from a stored representation

unset Unsets a variable

var_dump Dumps information about a variable

var_export Outputs or returns a string representation of a variable that can be parsed

Constants

define(name, value, true/false)

Aside from user-defined constants, there also a number of default PHP constants:

LINE Denotes the number of the current line in a file

FILE Is the full path and filename of the file

DIR The directory of the file

FUNCTION Name of the function

CLASS Class name, includes the namespace it was declared in

TRAIT The trait name, also includes the namespace

METHOD The class method name

NAMESPACE Name of the current namespace

PHP ARRAYS – GROUPED VALUES

Indexed arrays Arrays that have a numeric index

Associative arrays Arrays where the keys are named

Multidimensional arrays Arrays that contain one or more other arrays

Declaring an Array in PHP

$cms = array("WordPress", "Joomla", "Drupal");

echo "What is your favorite CMS? Is it ". $cms[0]. ", ". $cms[1]. " or ". $cms[2]. "?";

?>

Array Functions

array_change_key_case Changes all keys in an array to uppercase or lowercase

array_chunk Splits an array into chunks

array_column Retrieves the values from a single column in an array

array_combine Merges the keys from one array and the values from another into a new array

array_count_values Counts all values in an array

array_diff Compares arrays, returns the difference (values only)

array_diff_assoc Compares arrays, returns the difference (values and keys)

array_diff_key Compares arrays, returns the difference (keys only)

array_pad Inserts a specified number of items (with a specified value) into an array

array_pop Deletes an element from the end of an array

array_product Calculate the product of all values in an array

array_push Push one or several elements to the end of the array

array_rand Pick one or more random entries out of an array

array_reduce Reduce the array to a single string using a user-defined function

array_replace Replaces elements in the first array with values from following arrays

array_replace_recursive Recursively replaces elements from later arrays into the first array

array_reverse Returns an array in reverse order

array_search Searches the array for a given value and returns the first key if successful

array_shift Shifts an element from the beginning of an array

array_slice Extracts a slice of an array

array_splice Removes a portion of the array and replaces it

array_sum Calculate the sum of the values in an array

array_udiff Compare arrays and return the difference using a user function (values only)

array_udiff_assoc Compare arrays and return the difference using a default and a user function (keys and values)

array_udiff_uassoc Compare arrays and return the difference using two user functions (values and keys)

array_uintersect Compare arrays and return the matches via user function (values only)

array_uintersect_assoc Compare arrays and return the matches via a default user function (keys and values)

array_uintersect_uassoc Compare arrays and return the matches via two user functions (keys and values)

array_unique Removes duplicate values from an array

array_unshift Adds one or more elements to the beginning of an array

array_values Returns all values of an array

array_walk Applies a user function to every element in an array

array_walk_recursive Recursively applies a user function to every element of an array

arsort Sorts an associative array in descending order according to the value

asort Sorts an associative array in ascending order according to the value

compact Create an array containing variables and their values

count Count all elements in an array, alternatively use sizeof

current Returns the current element in an array, an alternative is pos

uasort Sorts an array with a user-defined comparison function

uksort Arrange an array by keys using a user-defined comparison function

usort Categorize an array by values using a comparison function defined by the user

PHP STRINGS

Defining Strings

Single quotes This is the simplest way. Just wrap your text in ' markers and PHP will handle it as a string.

Double quotes As an alternative you can use ". When you do, it’s possible to use the escape characters below to display special characters.

heredoc Begin a string with <<< and an identifier, then put the string in a new line. Close it in another line by repeating the identifier. heredoc behaves like double-quoted strings.

nowdoc Is what heredoc is for double-quoted strings but for single quotes. It works the same way and eliminates the need for escape characters.

Escape Characters

\n — Linefeed

\r — Carriage return

\t — Horizontal tab

\v — Vertical tab

\e — Escape

\f — Form feed

\ — Backslash

$ — Dollar sign

\’ — Single quote

" — Double quote

[0-7]{1,3} — Character in octal notation

\x[0-9A-Fa-f]{1,2} — Character in hexadecimal notation

\u{[0-9A-Fa-f]+} — String as UTF-8 representation

String Functions

addcslashes() Returns a string with backslashes in front of specified characters

addslashes() Returns a string with backslashes in front of characters that need to be escaped

bin2hex() Converts a string of ASCII characters to hexadecimal values

chop() Removes space or other characters from the right end of a string

chr() Returns a character from a specified ASCII value

chunk_split() Splits a string into a series of smaller chunks

convert_cyr_string() Converts a string from a Cyrillic character set to another

convert_uudecode() Decodes a uuencoded string

convert_uuencode() Encodes a string using uuencode

count_chars() Returns information about the characters in a string

crc32() Calculates a 32-bit CRC for a string

crypt() Returns a hashed string

md5() Calculates the MD5 hash of a string and returns it

md5_file() Calculates the MD5 hash of a file

metaphone() Provides the metaphone key of a string

money_format() Returns a string as a currency string

nl_langinfo() Gives specific locale information

nl2br() Inserts HTML line breaks for each new line in a string

number_format() Formats a number including grouped thousands

ord() Returns the ASCII value of a string’s first character

parse_str() Parses a string into variables

print() Outputs one or several strings

printf() Outputs a formatted string

quoted_printable_decode() Converts a quoted-printable string to 8-bit binary

quoted_printable_encode() Goes from 8-bit string to a quoted-printable string

quotemeta() Returns a string with a backslash before metacharacters

rtrim() Strips whitespace or other characters from the right side of a string

setlocale() Sets locale information

sha1() Calculates a string’s SHA-1 hash

sha1_file() Does the same for a file

similar_text() Determines the similarity between two strings

soundex() Calculates the soundex key of a string

sprintf() Returns a formatted string

sscanf() Parses input from a string according to a specified format

str_getcsv() Parses a CSV string into an array

str_ireplace() Replaces specified characters in a string with specified replacements (case-insensitive)

str_pad() Pads a string to a specified length

str_repeat() Repeats a string a preset number of times

str_replace() Replaces specified characters in a string (case-sensitive)

str_rot13() Performs ROT13 encoding on a string

str_shuffle() Randomly shuffles the characters in a string

str_split() Splits strings into arrays

str_word_count() Returns the number of words in a string

strcasecmp() Case-insensitive comparison of two strings

strcmp() Binary safe string comparison (case sensitive)

strrev() Reverses a string

strripos() Finds the position of the last occurrence of a string’s substring (case insensitive)

strrpos() Same as strripos() but case sensitive

strspn() The number of characters in a string with only characters from a specified list

strstr() Case-sensitive search for the first occurrence of a string inside another string

strtok() Splits a string into smaller chunks

strtolower() Converts all characters in a string to lowercase

strtoupper() Same but for uppercase letters

strtr() Translates certain characters in a string, alternative: strchr()

substr() Returns a specified part of a string

substr_compare() Compares two strings from a specified start position up to a certain length, optionally case sensitive

substr_count() Counts the number of times a substring occurs within a string

substr_replace() Replaces a substring with something else

trim() Removes space or other characters from both sides of a string

ucfirst() Transforms the first character of a string to uppercase

ucwords() Converts the first character of every word in a string to uppercase

vfprintf() Writes a formatted string to a specified output stream

vprintf() Outputs a formatted string

vsprintf() Writes a formatted string to a variable

wordwrap() Shortens a string to a given number of characters

PHP OPERATORS

Arithmetic Operators

  • — Addition
  • — Subtraction
  • — Multiplication

/ — Division

% — Modulo (the remainder of value divided by another)

** — Exponentiation

Assignment Operators

+= — a += b is the same as a = a + b

-= — a -= b is the same as a = a – b

*= — a *= b is the same as a = a * b

/= — a /= b is the same as a = a / b

%= — a %= b is the same as a = a % b

Comparison Operators

== — Equal