See the PHP Manual for more information.
no posts found
no posts found
Arrays
Define an array
// Define an array.
$my_array = [a,b,c,d];
// Define an array (the old standard way < php 5.3).
$my_array = array(a,b,c,d);
Get the last element of an array
$lastEl = array_pop((array_slice($array, -1)));
Count the number of element in an array
$total = count($array);
Objects and Classes
In Object-Oriented Programming a container called a class holds a collection of functions (called methods when they are in a class). A class does nothing until an instance of it is created (instantiated). Once an instance of a class has been created the methods can be used. A program can use any number of classes.
Defining a Class
<?php
class SimpleClass
{
// Property declaration.
public $var = 'a default value';
// Constant declaration.
const VAR_NAME = 'a value';
// Class constructor method.
public function __construct()
{
echo self::VAR_NAME;
}
// Method declaration.
public function displayVar() {
echo $this->var;
}
}
?>
Instantiate a class
- PHP library classes are always at the root so simply use one slash.
// Standard class instantiation.
$my_class_instance = new MyClass();
$my_class_instance = new child\MyChildClass();
$my_class_instance = new \MyRootLevelClass();
// Instantiate a new empty class
$my_empty_class_instance = new stdClass();
$my_empty_class_instance = new (object)[]; // Optionally as of PHP 5.4
Instantiate a class dynamically
// Instantiate a class dynamically
$class_name = '\\Foo\\Bar\\MyClass';
$my_class_instance = new $class_name();
Convert an Object to an Array
$array = json_decode(json_encode($object), true);
Calling functions and methods
// Call a function programmatically
$func = 'my_function';
$func('param1'); // calls my_function('param1');
// Call a class method programmatically
$my_method_name = 'foo';
$my_class = new MyClass();
$my_class->$my_method_name(); // calls the MyClass->foo() method.
Convert an object to an array
function obj_to_array($obj)
{
return (array) $obj;
}
Autoloading
In order to instantiate (create an instance of) a class which is defined in a separate file, that file must be included or required into the file currently being executed.
Control Structures
Ternary Operators
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true.
Alt Syntax (for views)
PHP offers an alternative syntax for some of its control structures; namely, if
, while
, for
, foreach
, and switch
. In each case, the basic form of the alternate syntax is to change the opening brace to a colon :
and the closing brace to endif;
, endwhile;
, endfor;
, endforeach;
, or endswitch;
, respectively.
<?php if ($x == 1): ?>
...
<?php else: ?>
...
<?php endif; ?>
Filter and Sanitize
filter_input
// Sanitize input
if (is_numeric($_POST[$post_key])) {
$filtered_db_inputs[$post_key] = filter_input(INPUT_POST, $post_key, FILTER_SANITIZE_NUMBER_INT);
} else {
$filtered_db_inputs[$post_key] = filter_input(INPUT_POST, $post_key, FILTER_SANITIZE_STRING);
}
Trimming
Use trim
, ltrim
, and rtrim
to remove substrings from the beginning and end of a string.
$string = ' _hello_ ';
$trimmed = trim( $string ); // Returns "_hello_"
echo trim( $trimmed, '_' ); // Returns "hello"
// Warning 'ltrim' and 'rtrim' remove all instances of all the characters passed
// to the function. It is not a string definition.
echo ltrim( $string, ' _' ); // Returns "hello_ "
echo = rtrim( $string, '_ ' ); // Returns " _hello"
HTML and DOM Parsing
DOMDocument
- PHP core comes with a very handy HTML parser called DOMDocument.
- Parse html DOM with DOMDocument
// Create a new DOMDocument object.
$dom = new DOMDocument;
// Load the HTML page into the object.
$dom->loadHTML($html);
// Once the HTML is loaded into the object, access nodes and child elements:
// Get an element by it's ID.
$my_div_obj = $dom->getElementById('mydiv');
// Get all elements of a type.
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) {
echo $dom->saveHTML($anchor); // Prints the text-only content of the anchor.
}
Remove HTML Tag Attribute
function remove_html_attribute($html, $attribute_name) {
return preg_replace('/(<[^>]+)' . $attribute_name . '=".*?"/i', '$1', $html);
}
echo remove_html_attribute('<div style="color:#CCC;"></div>', 'style'); // Prints '<div></div>'
Get all image tags
preg_match_all('/
]+>/i',$html, $result);
Bootstrap a PHP App
Route all requests the server to one index.php
file. This technique is known as bootstrapping. It transfers the routing responsibility from the web server to the app.
The first step is to setup an Apache virtual host which will follow SymLinks and allow overrides from mod rewrite.
# httpd.conf
<VirtualHost *>
ServerName mydomain.com
DocumentRoot "/abs/path/to/mywebroot"
<Directory />
Options Indexes FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>
A .htaccess
file must exist in the same directory as the index.php
file.
# .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)/$ /$1 [L,R=301] # This enforces NO trailing slashes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>