Shortening your PHP Code

Written by James McDonald

July 30, 2015

Learning PHP using firstly CakePHP 2 and now moving onto CakePHP 3 I’m finding there are some ways PHP has changed to allow you to write less and get the same result.




    $myarray = array(
                  'one' => 'One',
                  'two' => 'Two',
                  'three' => 'Three'




    $myarray = [ 
             'one' => 'One', 
             'two' => 'Two', 
             'three' => 'Three' 


Short Tags

# long tags
<?php echo "Hello World"; ?>

# short tags
<? echo "Hello World"; ?>

And also a cool shortening of echo

# instead of 
<?php echo "Echo This!"; ?>

# you can do
<?= "Echo This!"; ?>

Speaking of differences as PHP gets new features. If you are wondering why the CakePHP 3 code looks different (the namespace and use keywords at the top of each file) check out for an explanation of what they are and why they are very useful (especially if you create or use 3rd party PHP libraries)


namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;
     * Suburbs Controller
     * @property \App\Model\Table\SuburbsTable $Suburbs
class SuburbsController extends AppController


Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…

Test your AV client with Eicar is a special file that is NOT malicious (if gotten from the right place) it is simply a text file with a...