Our PHP cheat sheet aims to help anyone trying to get proficient in or improve their knowledge of PHP. The programming language is among the most popular in web development. It’s in the heart of WordPress, the world’s most popular CMS, and also forms the base of other platforms like Joomla and Drupal.
(Don’t miss our comparison of the three.). Aside from that, PHP is an Open Source and thus free to use.
Scalability W and High Availability W
Probability Theory W
Consequently, the user doesn’t see the code itself but only the result. By GgiaEsquema-proxy-internet.svg: Randomicc [CC BY-SA 3.0], from Wikimedia Commons. The programming language is relatively easy to learn for beginners, but it also offers a lot of advanced possibilities for veteran programmers.
SageMath (Sage, SAGE)W
Like many other languages, PHP also has the ability to add comments. This is important for annotating your code for human readers but in a way that the browser doesn’t try to execute it. In PHP, you have several ways for that:. // — Denotes comments that only span one line.
Math, Mathematics W
# — Another way of producing single-line comments. /*..*/ — Everything between /* and */ is not executed, also works across several lines. A common example of the use of comments is WordPress theme headers:. In PHP, data is commonly output using echo or print. For example, the title of this blog post might be displayed on a page like this:.
The two commands echo and print are pretty much the same. The only difference is that the former has no return value and can take several parameters, while the latter has a return value of 1 and can only take one argument. An important note: Like all other PHP commands, functions echo and print are not case sensitive. That means that when you write ECHO, EcHo, eCHO or any other variation, they will continue to work.
As you will learn further on, that doesn’t apply to everything. Functions are shortcuts for commonly used chunks of code. They make programming much easier because you don’t have to re-use long code snippets. Instead, you create them once and use the shortcuts when you need them.
It’s possible to create your own PHP functions but there also many built into the programming language. Much of this PHP cheat sheet is devoted to that. The basic syntax to create a function:. Quick explanation: the first part is the function of a name (reminder: function names are not case sensitive). After that, everything between the curly braces is what the function does when called.
Similarly to most other programming languages, PHP lets you work with variables and constants. These are pieces of code that store different kinds of information. To do anything with variables, you first need to define them.
In PHP, you denote a variable using the $ sign and assign its value using =. A typical example:. A few important points:. Variables need to start with a letter or underscore (_) and can only be comprised of alpha-numeric characters. PHP variables are case sensitive, that means $myVar and $myvar are not the same thing. If your variable consists of more than one word either write it $my_variable or $myVariable. Variables can take on different 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. It 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.
TTCN-3 (Testing and Test Control Notation version 3) W
Resources — These are references to functions and resources outside of PHP. NULL — A variable that is NULL doesn’t have any value. There is no need to declare PHP variables in a certain way. They automatically take on the type of data they contain. Variables can be available in different scopes, meaning the part of a script you can access them.
This can be global, local and static. Any variable declared outside of a function is available globally. That means it can be accessed outside of a function as well. If you declare a variable inside a function, it will have a local scope. The consequence is that it can only be accessed within that function.
A way around this is to prepend a local variable with global. That way, it becomes part of the global scope. In both cases, the variable becomes part of the $GLOBALS variable mentioned below. Finally, it’s also possible to add static in front of a local variable.
- That way, it won’t be deleted after its function is executed and can be reused.
- PHP also comes with a number of default variables called superglobals.
- That’s because they are accessible from anywhere, regardless of scope.
- $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.
- Aside from that, there are a whole bunch of functions to work with variables:.
- 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.
rpm - Red Hat Package Manager W
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. is_callable — Verify whether you can call the contents of a variable as a function.
- is_countable — Check whether the contents of a variable are countable.
- is_float — Find out if the type of a variable is float, alternatives: is_double and is_real.
- is_int — Check if the type of a variable is an integer, is_integer and is_long also works.
- is_iterable — Verify that a variable’s content is an iterable value.
- is_null — Checks whether a variable’s value is NULL.
- is_numeric — Find out if a variable is a number or a numeric string.
is_object — Determines whether a variable is an object. is_resource — Check if a variable is a resource. is_scalar — Tests if a variable is a scalar. is_string — Find out whether the type of a variable is a string.
isset — Determine if a variable has been set and is not NULL. print_r — Provides human-readable information about a variable. serialize — Generates a representation of a value that is storable. settype — Sets a variable’s type. strval — Retrieves the string value of a variable.
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. Aside from variables, you can also define constants which also store values.
In contrast to variables their value can not be changed, it’s locked in. In PHP you can define a constant:. The first is the name, the second the constant’s value and the third parameter whether its name should be case sensitive (the default is false). Constants are useful since they allow you to change the value for an entire script in one place instead of having to replace every instance of it.
They are also global in nature, meaning they can be accessed from anywhere. 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. Arrays are a way to organize several values in a single variable so that they can be used together. While functions are for blocks of code, arrays are for the values – a placeholder for larger chunks of information. In PHP there are different types of arrays:.
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. Arrays in PHP are created with the array() function. Array keys can either be strings or integers. PHP offers a multitude of default functions for working with arrays:. 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_diff_uassoc — Compares arrays (keys and values) through a user callback function.