code • PHP - martindubenet/wed-dev-design GitHub Wiki

Very basic PHP stuff that I keep on forgetting after a while...

Shorthands

Original (long) Shorthand
<?php echo( $my_var ); ?> <?= $my_var ?>

 

Plugins

  1. Composer : Same as npmJs but for PHP.
  2. scssphp : SCSS compiler written in PHP. ➥ Github clone

 

Tips

Return and start on a new line. (this requires double quotes characters)

echo "\r\n";

Logics

See logical and comparaison Operators

If a var exist and is « NOT empty » : « ! + empty »

This is fundamentally a negative check so in order to use it you need to add the negation « ! » as prefex to make it positive.

In the following example

<?php
if (!empty( $var1 )) {
	echo '<code>' . $var2 . '</code>';
}
?>

If a var value equal to « false » OR « is NOT set » (meaning it does not exist)

<?php
if ( $var1 == false || (!isset( $var1 )) ) {
	echo '<code>' . $var2 . '</code>';
}
?>

Read external dataset from Json file

This works fine for a simple single level of data

$jsonFile 	= utf8_encode( file_get_contents( "../any_path/file.json" ) );
// Decode JSON data as a PHP associative array
$phpArray	= json_decode($jsonFile, true);

// Loop through the associative array of a multi-level Json data node
foreach( $phpArray as $loopedItem ) {
	echo '<dt>'
		.$phpArray["unlooping_jsonNode"]. 
		'</dt><dd>'
		.$loopedItem["parentContainer_jsonNode"]["childData_jsonNode"].
		'</dt>';
}

Localhost VS other server

Because when developping with MAMP or WAMP local servers we sometimes forget to reset the "OTHER" server... It's alway useful to have those at hand.

$this_server_ip		= $_SERVER['REMOTE_ADDR'];
$localhost_ip		= "127.0.0.1";

if ( ( $this_server_ip == $localhost_ip ) || (empty( $rootPath )) ) {
	$rootPath = "http://localhost/";
} else {
	$rootPath = "/";
}

Roots

dirname(__FILE__)
<?php require_once(dirname(__FILE__) . '/inc/variables.php'); ?>

or

$projectSlug = '/vrak2014/';
$serverRoot = $_SERVER['DOCUMENT_ROOT'];
$rootPath = $serverRoot.$projectSlug;
⚠️ **GitHub.com Fallback** ⚠️