PHP : short syntax (cheat sheet)

Whether you need them to shorten your code, to understand code from someone else, or to use them to write your templates, here is a list of short syntax you can use in PHP :

Output : echo

For templates :

<?= $myVar ?>

which is similar to :

<?php echo $myVar; ?>

Ternary operator (conditional operator)

The combination of question mark and colon represent a specific syntax reserved to ternary operators.

$myVar = (CONDITION) ? VALUE_1 : VALUE_2;

function $myFunction()
{
  return (CONDITION) ? VALUE_1 : VALUE_2;
}

which are respectively similar to :

if (CONDITION) $myVar = VALUE_1;
else $myVar = VALUE_2;

function $myFunction()
{
  if (CONDITION) return VALUE_1;
  else return VALUE_2;
}

Single conditional structures : with an output

This only works with print statement (because it actually always returns 1, thus == true).

(CONDITION) AND print(SOMETHING);

which is similar to :

if (CONDITION)
{
  print(SOMETHING);
}

Conditional structures : if … elseif … else

For pure PHP code :

if (CONDITION 1):
  INSTRUCTION 1;
  INSTRUCTION 2;
elseif (CONDITION 2):
  INSTRUCTION 3;
else:
  INSTRUCTION 3;
endif;

For templates :

<?php if (CONDITION 1): ?>
...
<?php elseif (CONDITION 2): ?>
...
<?php else: ?>
...
<?php endif ?>

Conditional structures : switch … case

For templates :

Also, becareful with any space between the switch and the first case : this is really not a good idea to close PHP tag et reopen it between them. FYI: I really don’t like switches within templates.

<?php switch($myVar):
case 1: ?>
...
<?php break;?>
<?php case 2: ?>
...
<?php break;?>
<?php endswitch;?>

Loop structures : for / foreach / while

For templates :

<?php for($i=0; $i<$i_max; $i++): ?>
...
<?php endfor ?>

<?php while (CONDITION): ?>
...
<?php endwhile ?>

<?php foreach($myArray as $value): ?>
...
<?php endforeach ?>

PHP : How to install PHP Accelerator in Xampp ?

To install PHP Accelerator in Xampp, you need first to go to your php.ini file (i.e. within C:xamppphp directory) and add this line inside Dynamic Extensions part :

Then you need :

  1. to show you PHP configuration via the PHP function phpinfo()
  2. to get 2 precious informations :
    PHPInfo 2
    PHPInfo 1
    x86 or x64, and TS (Thread Safe) or NTS (Non Thread Safe)
  3. to download the corresponding DLL (including your PHP version):
    http://pecl.php.net/package/APCu/4.0.8/windows
    (PHP 7: http://pecl.php.net/package/APCu/5.1.3/windows)
  4. to copy/paste the DLL file within your extensions directory
  5. to edit your php.ini file (i.e. within C:xamppphp directory)
  6. and add this line inside Dynamic Extensions part :
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;

[...]

extension=php_apcu.dll

Eventually don’t forget to restart Apache !

PHP : How to install Intl extension in Xampp ?

The PHP Internationalization extension is used, amongst others, by Symfony (for validators). This extension allows you to write codes like this one :

$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $formatter->format(1234567.89); // 1,234,567.89

$formatter = new NumberFormatter('fr_FR', NumberFormatter::DECIMAL);
echo $formatter->format(1234567.89); // 1 234 567,89

$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE); // USD

$formatter = new NumberFormatter('pt_BR', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE); // BRL

and so much more, including formatting of currency, number and date/time as well as UCA-conformant collations (customizable method to compare two strings).

To activate this extension in Xampp, just edit your php.ini (i.e. in C:\xampp\php directory) and remove the semicolon to uncomment this line :

;extension=php_intl.dll

Eventually don’t forget to restart Apache !

PHP : How to use 4 methods (DELETE, GET, POST, PUT) in a RESTful API client using Curl ?

Finishing my first release of PhpRestDoc I had to develop a cross-method solution to allow users to test REST API requesting directly from the documentation and get 3 parts of the API response :

  • HTTP Status Code,
  • Header,
  • Body,

through 4 different methods :

  • DELETE,
  • GET,
  • POST,
  • PUT.

Also I wanted to be able to set what content type I wanted to get (JSON, XML, etc).

I then fully commented to share you the source code I wrote to achieve that :

/*
  Set the Request Url (without Parameters) here
*/
$api_request_url = 'https://api.example.com/user/info/';

/*
  Which Request Method do I want to use ?
  DELETE, GET, POST or PUT
*/
$method_name = 'GET';

/*
  Let's set all Request Parameters (api_key, token, user_id, etc)
*/
$api_request_parameters = array(
  'api_key' => 'gF7mc05157W726sL',
  'token' => 'hnFGJSpNzMzft8GE8AVTdvyZaydNYorgthkO46Rt',
  'user_id' => 5428
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

if ($method_name == 'DELETE')
{
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_request_parameters));
}

if ($method_name == 'GET')
{
  $api_request_url .= '?' . http_build_query($api_request_parameters);
}

if ($method_name == 'POST')
{
  curl_setopt($ch, CURLOPT_POST, TRUE);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_request_parameters));
}

if ($method_name == 'PUT')
{
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_request_parameters));
}

/*
  Here you can set the Response Content Type you prefer to get :
  application/json, application/xml, text/html, text/plain, etc
*/
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));

/*
  Let's give the Request Url to Curl
*/
curl_setopt($ch, CURLOPT_URL, $api_request_url);

/*
  Yes we want to get the Response Header
  (it will be mixed with the response body but we'll separate that after)
*/
curl_setopt($ch, CURLOPT_HEADER, TRUE);

/*
  Allows Curl to connect to an API server through HTTPS
*/
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

/*
  Let's get the Response !
*/
$api_response = curl_exec($ch);

/*
  We need to get Curl infos for the header_size and the http_code
*/
$api_response_info = curl_getinfo($ch);

/*
  Don't forget to close Curl
*/
curl_close($ch);

/*
  Here we separate the Response Header from the Response Body
*/
$api_response_header = trim(substr($api_response, 0, $api_response_info['header_size']));
$api_response_body = substr($api_response, $api_response_info['header_size']);

// Response HTTP Status Code
echo $api_response_info['http_code'];

// Response Header
echo $api_response_header;

// Response Body
echo $api_response_body;

PHP : How to execute a MySQLi query after a multi_query (for PHP > 5.3) ?

I just got a problem today : I needed to execute a $mysqli->query() after a $mysqli->multi_query() and it didn’t work. Here is the error I got :

Fatal error: Call to a member function fetch_array() on a non-object in [...]

I then checked the PHP Documentation about mysqli::multi_query and tried to use the solution suggested by jcn50 but I got this error :

Strict Standards: mysqli::next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method in [...]

Because it only works for PHP <= 5.2.

I then find a solution that is logic :

$mysqli->multi_query("Many MySQL queries concatenated by a semicolon");

while ($mysqli->next_result()) // flush multi_queries
{
  if (!$mysqli->more_results()) break;
}

$mysqli->query("MySQL statement #1");
$mysqli->query("MySQL statement #2");
$mysqli->query("MySQL statement #3");