5 New Features In PHP 7 That You Should Have A Look At

PHP is by far, the most preferred programming language. But is PHP 7 the most exciting releases of them all? Yes. The whole PHP community and the people linked to PHP, are all excited to welcome the biggest release for PHP in decades. It surely adds more versatility to the already versatile language.

But you must be wondering why PHP named its latest release PHP 7 and not PHP 6. Reason behind it is that, many of the PHP 6 releases were already implemented in PHP 5.3 and later, there was not really a proper reason just to change the name. What I am trying to say here is that we haven’t missed anything. Just to avoid the confusion with a dead project, PHP’s latest release was named to PHP 7.

Is This Hype Valid for PHP 7? What It Actually Brings Forth for the Developers?Hop on and let’s take a deeper dive. Let’s check out what new features PHP 7 has to offer. And what improvements those features will bring forth.

 

1. Speed Improvement

The developers for the PHP 7 has done a pretty commendable job here. Now your PHP codebase uses less memory and gives you even more performance than before. After it’s release, internet was overloaded with benchmarks which were really promising. It is almost a 2x increase inserver response times with PHP 7. For further details on benchmarks click here.

2. Implementation of Type Declarations

The type declaration is used to specify the type of variable. PHP sets this automatically and because of which, PHP is a weakly typed language. PHP does not need you to declare the data type. Because of which, you could do radical things with the variables, like adding Float into String without resulting in an error. Type declaration helps you get the expected results. Making sure that only certain procedures can occur. Which makes the code understandable.

In the previous PHP versions, we could use type hinting method. This method specifies the type of an argument declaration in a function. But the issue with this method was that you can only use it with a function declaration. Which limits to only two types, a class name, and an array.

Scalar Type Declaration

PHP 7 has now added Scalar type declaration for int, float, string, and boolean. Adding scalar type declaration and enabling strict requirements ensures that more correct and well-documented PHP programs can be written. It also helps you in gaining more control over your code and make the code easier to read.

By default, on PHP 7, these declarations are non-strict. Which means that the type forging is possible. As if you pass a string starting with a number into a float type function, it grabs the number from in the start and skips everything else. Passing a float into a function that requires an int, that float will become int.

Non-Strict Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getSum(float $a, float $b) {
   return $a + $b;
}
getSum(6, "7 week");
//Here int(6) changed to float(6.0) and string “7 week” changed to float(7.0)
//with a “Notice: A non well formed numeric value encountered”
//returns float(13)
getSum(1.1, "2.2");
//Here string "2.2" is changed to float(2.2) without any notice
//returns float(3.3)
getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)

Here the getSum function receives 2 floats and adds them together returning the sum. When you use a non-strict type declaration in PHP 7. It will reforge these arguments to match the type specified in the function. Which means whatever the argument we pass, PHP will convert it to float.

Strict Example

PHP 7 additionally gives us the opportunity to strict the declaration type. It is achieved by adding “strict_types=1” on the very first line of the file. This ensures that any calls made to the functions specified must strictly adhere to the specified types. Strict is determined in the file in which the call to a function is made and not the file in which the function is defined.

While using a strict type-declaration, if a mismatch occurs, a “Fatal Error” occurs and we know that something is not functioning as desired. This helps in not causing random and confusing diagnose issues. Let’s just cut the talk and take a look at an example with strict types turned on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
declare(strict_types=1);
function getSum(float $a, float $b) {
    return $a + $b;
}
getSum(3, "2 week");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given
getSum(1.8,  "4.5");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given
getSum(3.1, 2);
// int(2) change to float(2.0)
//returns float(5.1)

Setting “declare strict_type” to “1”, the first two calls that pass a string produces a Fatal error: “Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given”. With only the exception in the third call, in which if you pass an integer for an argument instead of a float value, PHP will perform “widening”, which includes adding .0 at the end of the integer value. This returns (5.1).

Return Type Declarations

The third type of declaration that PHP 7 supports are a Return Type Declaration. It supports all similar type arguments as a return. Take look at the example of how to specify a return type declaration.

1
2
3
function getSum(float $a, float $b) : float {
}

Adding a return type ensures that only an expected value type returns. For the previous two examples if we set the return type float it will work the same. As the values being returned are already float. So we will be doing an example for int. return types.

Non-Strict Integer Example

Without the strict type declaration on, if we specify the return type as int for the previous examples, it will work the same. With just the difference being, that return will be forged to an integer. Which means it will truncate the float value and only returns the integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getSum(float $a, float $b) : int {
    return $a + $b;
}
getSum(6, "7 week");
// changes int(6) to float(6.0) & string(“7 week”) to float(7.0)
// returns int(13);
getSum(1.1, "2.2");
// changes string "2.2" to float(2.2)
// returns int(3.3)
getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)

Strict Integer Example

If we turn strict types on, we’ll get a Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned. For this case we’ll be casting our return value as an int. which then returns the truncated value.

1
2
3
4
5
6
7
8
9
declare(strict_types=1);
function getSum(float $a, float $b) : int {
    // return $a + $b;
    // The above statement shows Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned
    return (int)($a + $b); // truncate float like non-strict
}
getSum(3.1, 2); // changes int(2) to float(2.0) and returns int(5.1)

Benefits

These new implementations of Type Declaration certainly help in making the code easier to read. With PHP 7 you get a versatile type declaration methods which makes your life easier. You can even see at the start of the function, what is required and what will be returned.

3. Implementation of Error Handling

The next new feature we will be discussing are the new Error Handling techniques implemented in PHP 7. Handling fatal errors was a nightmare in previous versions of PHP. If a fatal error occurs it just simply stops the script rather than invoking the error handler. On a production server, this returns a blank white screen to your users, which in the end causes your credibility to drop.

But PHP 7 allows an exception to be thrown when an error occurs, rather than stopping the whole script. This doesn’t mean that Fatal errors are gone from PHP 7. They still exist i.e., an uncaught exception will still be a fatal error in PHP 7. One more thing to highlight here is that other types of errors like warnings and notices are unchanged in PHP 7. And exceptions are only thrown by fatal and recoverable errors only.

However, Error and Exception both in PHP 7 implements the new throwable class. This means both work almost the same way. Let’s see the new hierarchy to understand more.

-> Exception implements Throwable
    -> …
-> Error implements Throwable
    -> TypeError
    -> ParseError
    -> ArithmeticError
        -> DivisionByZeroError
    -> AssertionError

Under Error, PHP 7 now have some more specific errors. Which includes ParseError, TypeError, ArithmeticErrors and an AssertionError. Practically all errors that were fatal in PHP 5, now throw instances of Error in PHP 7, which in term help you to improve your code legibility.

4. New Operators

PHP 7 also brings us some new operators. Let’s just cut the talk and directly go through all the new operators.

Spaceship Operator

The first one in our list is the Spaceship Operator, also known as the Combined Comparison Operator. It is put together using three of the previous operators, namely, “<”, “=” and “>”. It looks something like this:

1
<=>

What this operator is useful for is that it will compare the value on the left to the value on the right and returns 3 different values. See the example below for further understanding.

1
2
3
4
5
6
7
$compareResult = $a <=> $b
if $a < $b it returns “-1” to the variable “compareResult”
if $a = $b it returns “0” to the variable “compareResult”
if $a > $b it returns “1” to the variable “compareResult”

A very useful operator. The most common use of this operator will be in sorting.

Null Coalesce Operator

Another new operator in PHP 7 is the Null Coalesce Operator. If it is not null it returns the left operand, otherwise, it returns the right operand. The thing worth mentioning here is that it won’t pop any notice if the left operand is a null variable.

1
$user = $userName ??  "v3ron";

In the above example, if the variable userName is not null, it will push that value to the variable “user”, or else “v3ron” will be assigned to the variable “user”.

Before PHP 7, something like this would be written as:

1
$user = isset($userName) ? $userName : “v3ron”;

And yes, these can be stacked which makes it much likely to be used. It will check each item from left to right until it finds one that is not null, it will use that value. For example:

5. CSPRNG Functions

The CSPRNG abbreviated as “Cryptographically Secure Pseudo-Random Number Generator” is an easy to use API. It provides an easy and reliable way to generate secure random integers and bytes for use within cryptographic contexts. It can be used especially for generating random passwords or password salt.

2 new functions have been introduced in PHP 7 to use namely, “random_int” and “random_bytes”. Let’s analyze a bit more to see what these two brings to the table for the developers.

Random Bytes

With random_bytes, you only supply a single argument that is the length of the random string which it will return in bytes. Take a look at the example for a better understanding.

1
2
3
4
5
$randomByte = random_bytes(10); // 10 is the length in bytes
var_dump(bin2hex($randomByte));
// output for the above code is: string(20) "5f655db3ae43c256937b"

These are bytes, not integers. For a random number or integer, you should use the random_int function.

Random Integers

This function generates secure random integers. When using random_int you supply two arguments, that are min and max. Which tells the minimum and maximum numbers for the random integer.

For example:

1
random_int(2,10);

The above code returns a random number between 2 and 10, including those two as well.

6. Conclusion

So much for all the new features. There are some features that have been removed in PHP 7, you can check them out by going to the deprecated features section in PHP 7.

Versions released before 5.5 are not compatible any longer. Now it is for you to decide whether to upgrade to PHP 7 for super fast speeds and update all your code accordingly. Or stay with the previous version of PHP.

Advertisements

PHP Libararies for working with MS Office

1. Microsoft Word

PHPWord – A library for working with Microsoft Word documents.
PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft Office Open XML (OOXML or OpenXML), OASIS Open Document Format for Office Applications (OpenDocument or ODF), Rich Text Format (RTF), HTML, and PDF.

2. Microsoft PowerPoint

PHPPowerPoint – A pure PHP library for writing presentations files.
PHPPowerPoint is a library written in pure PHP that provides a set of classes to write to different presentation file formats, i.e. Microsoft Office Open XML (OOXML or OpenXML) or OASIS Open Document Format for Office Applications (OpenDocument or ODF).

3. Microsoft Excel

PHPExcel – A pure PHP library for reading and writing spreadsheet files.
PHPExcel is a library written in pure PHP and providing a set of classes that allow you to write to and read from different spreadsheet file formats, like Excel (BIFF) .xls, Excel 2007 (OfficeOpenXML) .xlsx, CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML, … This project is built around Microsoft’s OpenXML standard and PHP.

ExcelAnt – Simple yet powerful Excel manipulation library for PHP 5.4+.
ExcelAnt is an Excel manipulation library for PHP 5.4. It currently works on top of PHPExcel.

4. Extra

Csv – A CSV data manipulation library.
Csv is a simple library to ease CSV parsing, writing and filtering in PHP. The goal of the library is to be powerful while remaining lightweight, by utilizing PHP native classes whenever possible.

5. The end

Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
Did we miss out anything? Do leave a comment below to let us know.

 

POSTing JSON Data With PHP cURL

I got this question the other day: how to send a POST request from PHP with correctly-formatted JSON data? I referred to the slides from my web services tutorial for the answer, and I thought I’d also put it here, with a bit of explanation. After all, publishing your slides is all very well, but if you didn’t see the actual tutorial, I often think they aren’t too useful.

We can’t send post fields, because we want to send JSON, not pretend to be a form (the merits of an API which accepts POST requests with data in form-format is an interesting debate). Instead, we create the correct JSON data, set that as the body of the POST request, and also set the headers correctly so that the server that receives this request will understand what we sent:

$data = array("name" => "Hagrid", "age" => "36");                                                                    
$data_string = json_encode($data);                                                                                   
                                                                                                                     
$ch = curl_init('http://api.local/rest/users');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   
                                                                                                                     
$result = curl_exec($ch);

All these settings are pretty well explained on the curl_setopt() page, but basically the idea is to set the request to be a POST request, set the json-encoded data to be the body, and then set the correct headers to describe that post body. The CURLOPT_RETURNTRANSFER is purely so that the response from the remote server gets placed in $result rather than echoed. If you’re sending JSON data with PHP, I hope this might help!

cURL Requests with PHP

Introduction

cURL allows transfer of data across a wide variety of protocols, and is a very powerful system. It’s widely used as a way to send data across websites, including things like API interaction and oAuth. cURL is unrestricted in what it can do, from the basic HTTP request, to the more complex FTP upload or interaction with an authentication enclosed HTTPS site. We’ll be looking at the simple difference between sending a GET and POST request and dealing with the returned response, as well as highlighting some useful parameters.

Basics

Before we can do anything with a cURL request, we need to first instantiate an instance of cURL – we can do this by calling the function curl_init();, which returns a cURL resource. This function takes one parameter which is the URL that you want to send the request to, however, in our case, we’ll hold off doing that for now and set it an alternatively way later.

Settings

Once we’ve got a cURL resource, we can begin to assign some settings, below is a list of some of the core ones that I set

  • CURLOPT_RETURNTRANSFER – Return the response as a string instead of outputting it to the screen
  • CURLOPT_CONNECTTIMEOUT – Number of seconds to spend attempting to connect
  • CURLOPT_TIMEOUT – Number of seconds to allow cURL to execute
  • CURLOPT_USERAGENT – Useragent string to use for request
  • CURLOPT_URL – URL to send request to
  • CURLOPT_POST – Send request as POST
  • CURLOPT_POSTFIELDS – Array of data to POST in request

We can set a setting by using the curl_setopt() method, which takes three parameters, the cURL resource, the setting and the value. So, to set the URL that we’re sending the request to as http://testcURL.com:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://testcURL.com');

As mentioned, we can set the URL by sending a parameter through when getting the cURL resource:

$curl = curl_init('http://testcURL.com');

It is possible to set multiple settings at one time by passing through an array of settings and values to the function curl_setopt_array():

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com'
));

Sending request

When all of the options are sent, and the request is ready to send, we can call the curl_exec() method which will execute the cURL request. This function can return three different things:

  • false – if there is an error executing the request
  • true – if the request executed without error and CURLOPT_RETURNTRANSFER is set to false
  • The result – if the request executed without error and CURLOPT_RETURNTRANSFER is set to true

Using the previous example, where we are wanting to get the result back, we would use the following:

$result = curl_exec($curl);

With $result now containing the response from the page – which might be JSON, a string or a full blown site’s HTML.

Close Request

When you’ve sent a request and got the result back, you should look to close the cURL request so that you can free up some system resources, this is as simple as calling the curl_close() method which as with all other functions takes the resource as its parameter.

GET Request

A GET request is the default request method that is used, and is very straight forward to use, infact all of the examples so far have been GET requests. If you want to send parameters along in the request you simply append them to the URL as a query string such as http://testcURL.com/?item1=value&item2=value2.

So for example to send a GET request to the above URL and return the result we would use:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com/?item1=value&item2=value2',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

POST Request

The sole difference between the POST and GET request syntax is the addition of one setting, two if you want to send some data. We’ll be setting CURLOPT_POST to true and sending an array of data through with the setting CURLOPT_POSTFIELDS

So for example switching the above GET request to be a POST request, we would use the following code:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://testcURL.com',
    CURLOPT_USERAGENT => 'Codular Sample cURL Request',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        item1 => 'value',
        item2 => 'value2'
    )
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

There you have a POST request that will work the same as our GET request above and return the response back to the script so that you can use it as you want.

Errors

As much as we all hate errors, you really need to take care to account for any eventuality with cURL as ultimately you will not have control over the site(s) that you are sending your request to, you cannot guarantee that the response will be in the format that you want, or that the site will even be available.

There are a few functions that you can use to handle errors and these are:

  • curl_error() – returns a string error message, will be blank '' if the request doesn’t fail.
  • curl_errno() – which will return the cURL error number which you can then look up on this page listing error codes.

An example usage would be:

if(!curl_exec($curl)){
    die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}

You might want to look at using the setting CURLOPT_FAILONERROR as true if you want any HTTP response code greater than 400 to cause an error, instead of returning the page HTML.

curl_exec($theEnd);

cURL is a behemoth, and has many many possibilities. Some sites might only serve pages to some user agents, and when working with APIs, some might request you send a specfici user agent, this is something to be aware of.

 

Source:  http://codular.com/

Can I Use Popular Framework Features Without a Framework?

If you’ve been wondering about this question, the answer is YES!

There are many tools and libraries in the PHP ecosystem that we can use when developing an application. Some of them are grouped in frameworks which provide us some preconfigured structure. But with such variety of tools, we can easily make our own structure according to our needs.

In this article I will take a look and list some popular libraries for the different technical needs of our applications, such as talking to the database, routing, providing output to the web and etc.

PHP, frameworks,

But first, let’s get back to basics and explain what a framework is.

According to the general definition:

Framework is a universal, reusable software platform to develop software applications, products and solutions. To simplify, it is kind of library, piece of software which provides web developers with code base and consistent, standardized ways of creating web applications.

Your project will have to choose from tons of PHP libraries, frameworks and components. In addition, there are many PHP libraries, frameworks and components to adopt from. And these are called project dependencies like Composer and PEAR. Until recently PHP didn’t find acceptable way to manage these project dependencies. Some of the dependencies explained below show how can you use PHP without frameworks.

  • Composer repositories like Composer, PEAR, VSC

A dependency manager which installs packages locally with package description and name and version. In basics, package is just a directory containing something. In this case, it is a PHP code, but in theory it could be anything.

Repository is a package source. Practically it is a list of packages/versions. The composer will search in all your repositories to find the packages your project requires.

  • Databases like MySQL, PostgreSQL, NoSQL

There will be times when your PHP code will use database to persist information and there are few options to connect and interact with your database.

  • Object-relational mapping (ORM) like Doctrine, Readbean, Eloquent

The ORM manages the translation of object into relational databases and vice-versa. This creates so-called “virtual object database” which can be used from within the programming language.

  • Templating like Twig, Blade, Mustache, Plain PHP Templates

Templates provide convenient way of separating the controller and domain logic from your presentation logic. They typically contain the HTML of the application, but may be also used for other formats such as XML. Templates are often referred to as “views” which make up part of the second component of the model-view-controller (MVC) software architecture pattern.

  • HTTP like Guzzle, Buzz, HTTPFul, Requests

This is protocol destined for sending documents back and forth over the World Wide Web. A protocol is a set of rules that is used to identify which messages can be transferred and which are suitable answers to other queries.

  • Mailers like PHPMailer, SwiftMailer, Stampie

Mailers are libraries used in order to give the application an ability to send mails.

  • File Systems like Gaufrette, Flysystem, CSV

Libraries for file manipulation and MIME (Multipurpose Internet Mail Extensions) type detection.

  • Testing like PHP Spec, PHP Unit

Writing automated tests for your PHP code is considered to be a best practice and can lead to well-build applications. Automated tests are a great tool for making sure your application does not break when you are making changes or adding new functionality and should not be ignored.

PHP, code, frameworks

However some of the dependencies will not be used by your application and may not be essential, therefore you can easily create your own PHP project containing custom dependencies that are most suitable for the project.

To sum up, using framework can bring to faster development as it tries to save your work by make you define an overly complex configuration that has to accommodate every possible use case.

The Best Way to Learn PHP

Learning something from scratch is almost always an arduous affair — you simply have no idea as to where to start, or not to start, to kick things off. I loathed learning about the idiosyncrasies of C++’s syntax when all I wanted to learn were some darn programming concepts. As I’m sure you can agree, this is a less than ideal situation.

This is where the Nettuts+ “The Best Way to Learn” series comes into the picture. This series is intended to be your blueprint, your road map, your plan of action for learning your topic of choice! You don’t have to worry about finding the best resources, sorting out the bad ones, and figuring out what to learn next. It’s all here. Just follow it, step by step.

Today, we’re going to figure out the best way to learn PHP.

If you need immediate help, try working with one of the experienced PHP developers on Envato Studio. They can fix PHP errors, add features, or even create new apps for you.

PHP developers on Envato Studio
PHP developers on Envato Studio

If you’re reading this, chances are that you’ve Googled a lot to decide which language to learn and how. And without a doubt, you must have run into a ton of articles about how language X is so much better than PHP – and PHP is going to die through obscurity soon.

Haters gonna hate!

As the popular saying goes, haters gonna hate! PHP has been at the helm of the web as you know it and that’s for a very good reason. It’s a mature language, has excellent documentation and a massive number of learning resources along with a great variety of utilities built around it.

And let’s not forget the sheer proliferation of hosts and frameworks PHP has spawned. Like Heroku like hosting? Don’t worry, there are a number of excellent options for PHP as well!

Tut image

You could just install PHP but it gets quite boring without a server and some sort of database to play around with. And as a beginner, it’s not really trivial work to get all of these installed and configure each to work with the others without issue.

This is where you grab a package such as XAMPP. These life savers typically install Apache, your web server, along with mySQL, a database system along with PHP significantly cutting down on set up time.

Bonus points if you’re the code monkey type and install everything by hand.

You can also try LAMP, WAMP…….

Before I send you off to alternate sources for PHP enlightenment, let me first refer you to our very own series for absolute beginners from none other than your favorite editor, Jeffrey Way.

In this series, over the course of 40+ screencasts, everything from installing PHP to variables, from functions to working with MySQL is covered.

For learning basics, w3schools can be a great place. try it……..

Tut image

Khan Academy may sound like an odd choice since there are no PHP lessons in there but trust me, it’s a good choice. What you can’t find in pure PHP, you can find in the basic of programming. For example, if you’re new to the entire programming hoopla, this is a great place to start.

Another great place to start is Lynda. Here at Envato we have immense respect for those teaching there — the content is usually top notch and cover their topics well. And they cover a vast range of topics as well. If you need a specific lesson, this is where you should begin.

The videos should give you an very good springboard, but, hopefully, hungry for more knowledge. The below books should give you a more elaborate introduction and lots of varied topics for you to devour.

If you feel bored reading the initial portions, good, just skip ahead to the portions where your head hurts.

Nettuts image

Author: David Powers

“So why another PHP book? Well, not everyone who uses PHP is a programmer. PHP is the most common dynamic web language used by designers, if their web sites require dynamic functionality, and there are hordes of novice users who want to set up dynamic web sites.”

Nettuts image

Author: Jason Lengstorf

“PHP for Absolute Beginners starts at the very beginning stages of web programming, showing even the most inexperienced web developer, through examples, how to build a basic content management system. The book dives directly into writing web applications with accompanying explanation rather than explaining elements of the language and then showing examples.”

Nettuts image

Author: Adam Trachtenberg

“PHP Cookbook has a wealth of solutions for problems that you’ll face regularly. With topics that range from beginner questions to advanced web programming techniques, this guide contains practical examples — or “recipes” — for anyone who uses this scripting language to generate dynamic web content.”

This is the perfect time to build something simple with your new found knowledge.

Alright! With all those information swirling inside, you should feel like a rockstar. If not, don’t worry, it’s completely normal. Talk to me later so we can share notes about how daft we feel.

This is the perfect time to try and build something simple with your new found knowledge. It’s best to not try to build something too complicated and fail though — it’s a lot more disheartening than you’d think. Imagine being rejected for the first time. Now multiply it by a few hundred and you’ll be close.

Since you’re just starting out, play it safe and build something absolutely basic like a CRUD app. Nothing major — a few inputs and an ‘uncool’ table to display saved results. This tiny exercise will test your knowledge of a lot of PHP basics including the much vaunted ‘interfacing with a database’ skill.

Feeling better now? You should! You gazed upon where there was naught and said ‘This won’t do!’ and created something from scratch. If it were me, I’d be pumped. Let’s use it to extend our knowledge a little more.

While a simple CRUD app is a great start, you’d ideally need more complicated. A simple login/user system is absolutely great for this.

You get to learn how sessions work, how basic authentication is done, how to implement basic security measure and a ton more.

Note: If you’re in need of a little guidance, start here.

Tut image

At this point, after creating a non-trivial system, you probably have noticed how repetitive some of the work is. Why the heck do you need to write your own sessions class or work on hashing passwords yourself? The answer, my friends, is to go with a lightweight framework.

A framework abstracts a lot of the repetitive, boilerplate features in your typical application thus freeing up your brain to actually getting things done.

Note: CodeIgniter, a very lightweight, yet powerful framework. If you prefer Kohana, we do that too!

Tut image

Now that you’ve been with a lightweight framework, you can now check out the alternate path — a full stack framework. A full stack framework typically ships with a lot more features including code generators, ORMs and an inbuilt server. An excellent choice would be CakePHP — the PHP equivalent of Rails.

The reason you need to check these out later is because there is a lot of ‘magic’ going on. Without a solid understanding of how lightweight frameworks work, it’s hard to really dig into the better featured ones since you’ll mostly be lost and won’t understand how things work.

Note: I recommends both FuelPHP and Laravel as top-notch, modern PHP frameworks.

 

With all that information behind you, giving you Indiana’s swagger, now is the time to build something truly awesome. This is the final destination for PHP nirvana — and the choice is up to you.

So what exactly should you be building? Here are a few ideas:

  • A blog is always a safe option. There are a ton of open source solutions for you to get inspiration for the software architecture and the functionality requirements are unambiguous.
  • It’s a little old school but a discussion board is another excellent choice. Moderator rights and post counts, ahoy! If you need a little guidance, this tutorial is a great place to start.
  • Or if you’re too hip for any of these, build yourself a project management application or even just a todo list. They’re always fun to build and you’ll almost always end up using it personally.

Of course, there are just suggestions. No one is stopping you from building a multi-user, realtime chatroom or a service which receives input from random internet strangers and lights up stuff in your room. No one’s judging, go crazy!

Development is as much about the workflow as much as it is about the code.

Development is as much about the workflow as much as it is about the code. Recently, a typical developer’s workflow has been massively improved by version control as well as platform as a service solutions.

Version control, as expected, frees you up from having to manage revisions manually while PaaS solutions save you from having to do a lot of sys admin work just to get your app to scale.

You can getting started with Git.

New techniques and tools are being introduced everyday.

The web development industry is rarely in a state of equilibrium — everything is changing all the time. New techniques and tools are being introduced everyday and it’s important that you not only read about them but also start contributing.

Find a little glitch in some framework? Submit a patch. Added some new functionality? Patch away! These not only earn you good karma but also valuable points on your resume.

And, oh, about the keeping up to date stuff? Subscribe to our feed and follow us  and I promise you’ll know all you need to know!

Tryruby

Even though that you are a master of the PHP domain, you can’t afford to, or shouldn’t, rest. PHP is a grand language but that doesn’t mean that it does absolutely everything perfectly.

There is an ever increasing number of new languages out there each adding their own spin to solving a very specific problem that you simply can’t afford to miss out on. And learning something new something doesn’t really wipe out knowledge gained earlier does it? Well, except Star Wars, of course. Those new movies were a crapshoot.

Ruby, Python and Clojure are some of the languages that I’m constantly amazed by and I think they deserve your attention as well. Neither of these languages are necessarily ‘better’ than PHP but each of them do things their own unique way and you owe yourself a chance to take a look and find out whether that approach is for you.

Well, this is the end of the road, partner! Hopefully, this plan can help you become a PHP master and, indeed, take over the world.

If you feel that I’m missing some obvious resources here, feel free to yell at me in the comments section below and I’ll update this article whilst crying silently. Thank you so much for reading!

21 Essential PHP Interview Questions – toptal.com

Consider the following code:

$str1 = 'yabadabadoo';
$str2 = 'yaba';
if (strpos($str1,$str2)) {
    echo "\"" . $str1 . "\" contains \"" . $str2 . "\"";
} else {
    echo "\"" . $str1 . "\" does not contain \"" . $str2 . "\"";
}

The output will be:

"yabadabadoo" does not contain "yaba"

Why? How can this code be fixed to work correctly?

The problem here is that strpos() returns the starting position index of $str1 in $str2 (if found), otherwise it returns false. So in this example, strpos() returns 0 (which is then coerced to false when referenced in the if statement). That’s why the code doesn’t work properly.

The correct solution would be to explicitly compare the value returned by strpos() to false as follows:

$str1 = 'yabadabadoo';
$str2 = 'yaba';
if (strpos($str1,$str2) !== false) {
    echo "\"" . $str1 . "\" contains \"" . $str2 . "\"";
} else {
    echo "\"" . $str1 . "\" does not contain \"" . $str2 . "\"";
}

Note that we used the !== operator, not just the != operator. If we use !=, we’ll be back to the problem that 0 is coerced to false when referenced in a boolean expression, so 0 != false will evaluate to false.

What will be the output of the code below and why?

$x = 5;
echo $x;
echo "<br />";
echo $x+++$x++;
echo "<br />";
echo $x;
echo "<br />";
echo $x---$x--;
echo "<br />";
echo $x;

What will be the values of $a and $b after the code below is executed? Explain your answer.

$a = '1';
$b = &$a;
$b = "2$b";

Both $a and $b will be equal to the string "21" after the above code is executed.

Here’s why:

The statement $b = &$a; sets $b equal to a reference to $a (as opposed to setting $b to the then-current value of $a). Thereafter, as long as $b remains a reference to $a, anything done to $a will affect $b and vice versa.

So when we subsequently execute the statement $b = "2$b", $b is set equal to the string "2" followed by the then-current value of $b (which is the same as $a) which is 1, so this results in $b being set equal to the string "21" (i.e., the concatenation of "2" and "1"). And, since $b is a reference to $a, this has the same affect on the value of $a, so both end up equal to "21".

What will be the output of each of the statements below and why?

var_dump(0123 == 123);
var_dump('0123' == 123);
var_dump('0123' === 123);

var_dump(0123 == 123) will output bool(false) because the leading 0 in 0123 tells the PHP interpreter to treat the value as octal (rather than decimal) value, and 123 octal is equal to 83 decimal, so the values are not equal.

var_dump('0123' == 123) will output bool(true) since the string 0123 will automatically be coerced to an integer when being compared with an integer value. Interestingly, when this conversion is performed, the leading 0 is ignored and the value is treated as a decimal (rather than octal) value, so the values are bother 123 (decimal) and are therefore equal.

var_dump('0123' === 123) outputs bool(false) since it performs a more strict comparison and does not do the automatic type coercion of the string to an integer.

What is the problem with the code below? What will it output? How can it be fixed?

$referenceTable = array();
$referenceTable['val1'] = array(1, 2);
$referenceTable['val2'] = 3;
$referenceTable['val3'] = array(4, 5);

$testArray = array();

$testArray = array_merge($testArray, $referenceTable['val1']);
var_dump($testArray);
$testArray = array_merge($testArray, $referenceTable['val2']);
var_dump($testArray);
$testArray = array_merge($testArray, $referenceTable['val3']);
var_dump($testArray);

The output will be as follows:

array(2) { [0]=> int(1) [1]=> int(2) }
NULL
NULL

You may also see two warnings generated, similar to the following:

Warning: array_merge(): Argument #2 is not an array
Warning: array_merge(): Argument #1 is not an array

The issue here is that, if either the first or second argument to array_merge() is not an array, the return value will be NULL. For example, although one might reasonably expect that a call such as array_merge($someValidArray, NULL) would simply return $someValidArray, it instead returns NULL! (And to make matters worse, this is not documented well at all in the PHP documentation.)

As a result, the call to $testArray = array_merge($testArray, $referenceTable['val2']) evaluates to $testArray = array_merge($testArray, 3) and, since 3 is not of type array, this call to array_merge() returns NULL, which in turn ends up setting $testArray equal to NULL. Then, when we get to the next call to array_merge(), $testArray is now NULL so array_merge() again returns NULL. (This also explains why the first warning complains about argument #2 and the second warning complains about argument #1.)

The fix for this is straightforward. If we simply typecast the second argument to an array, we will get the desired results. The corrected array_merge() calls would therefore be as follows:

$testArray = array_merge($testArray, (array)$referenceTable['val1']);
var_dump($testArray);
$testArray = array_merge($testArray, (array)$referenceTable['val2']);
var_dump($testArray);
$testArray = array_merge($testArray, (array)$referenceTable['val3']);
var_dump($testArray);

which will yield the following output (and no warnings):

array(2) { [0]=> int(1) [1]=> int(2) } 
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } 
array(5) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) }

What will this code output and why?

$x = true and false;
var_dump($x);

Surprisingly to many, the above code will output bool(true) seeming to imply that the and operator is behaving instead as an or.

The issue here is that the = operator takes precedence over the and operator in order of operations, so the statement $x = true and false ends up being functionally equivalent to:

$x = true;       // sets $x equal to true
true and false;  // results in false, but has no affect on anything

This is, incidentally, a great example of why using parentheses to clearly specify your intent is generally a good practice, in any language. For example, if the above statement $x = true and false were replaced with $x = (true and false), then $x would be set to false as expected.

What will $x be equal to after the statement $x = 3 + "15%" + "$25"?

The correct answer is 18.

Here’s why:

PHP supports automatic type conversion based on the context in which a variable or value is being used.

If you perform an arithmetic operation on an expression that contains a string, that string will be interpreted as the appropriate numeric type for the purposes of evaluating the expression. So, if the string begins with one or more numeric characters, the remainder of the string (if any) will be ignored and the numeric value is interpreted as the appropriate numeric type. On the other hand, if the string begins with a non-numeric character, then it will evaluate to zero.

With that understanding, we can see that "15%" evaluates to the numeric value 15 and "$25" evaluates to the numeric value zero, which explains why the result of the statement $x = 3 + "15%" + "$25" is 18 (i.e., 3 + 15 + 0).

After the code below is executed, what will be the value of $text and what will strlen($text) return? Explain your answer.

$text = 'John ';
$text[10] = 'Doe';

After the above code is executed, the value of $text will be the string “John D” (i.e., “John”, followed by 5 spaces, followed by “D”) and strlen($text) will return 11.

There are two things going on here.

First of all, since $text is a string, setting a single element of $text simply sets that single character to the value specified. The statement $text[10] = 'Doe' therefore sets that single character to 'D' (i.e., the first character in the string "Doe", since an element of a string can only be a single character).

Secondly, $text[10] = 'Doe' says to set the 11th character of the string (remember that indices are zero-based) to 'D'. Prior to that statement, though, the length of the string $text ("John ") was only 5. Whereas compilers or interpreters in other languages might barf (with something akin to an out-of-bounds-index error) when you then attempt to set the 11th character of a 5 character string, PHP instead is very “accommodating” and instead allows this and sets all intermediate characters to blanks.

PHP_INT_MAX is a PHP constant that corresponds to the largest supported integer value (value is based on the version of PHP being run and the platform it is running on).

Assume that var_dump(PHP_INT_MAX) will yield int(9223372036854775807).

In that case, what will be the result of var_dump(PHP_INT_MAX + 1)? Also, what will be the result of var_dump((int)(PHP_INT_MAX + 1))?

NOTE: It’s not important to supply the exact value when answering the question, but rather to explain what will happen and why.

The result of var_dump(PHP_INT_MAX + 1) will be displayed as a double (in the case of this specific example, it will display double(9.2233720368548E+18)). The key here is for the candidate to know that PHP handles large integers by converting them to doubles (which can store larger values).

And interestingly, the result of var_dump((int)(PHP_INT_MAX + 1)) will be displayed as a negative number (in the case of this specific example, it will display int(-9223372036854775808)). Again, the key here is for the candidate to know that the value will be displayed as a negative number, not to know the precise value.

How would you sort an array of strings to their natural case-insensitive order, while maintaing their original index association?

For example, the following array:

array(
	'0' => 'z1',
	'1' => 'Z10',
	'2' => 'z12',
	'3' => 'Z2',
	'4' => 'z3',
)

After sorting, should become:

array(
	'0' => 'z1',
	'3' => 'Z2',
	'4' => 'z3',
	'1' => 'Z10',
	'2' => 'z12',
)

The trick to solving this problem is to use three special flags with the standard asort() library function:

asort($arr, SORT_STRING|SORT_FLAG_CASE|SORT_NATURAL)

The function asort() is a variant of the standard function sort() that preserves the index association. The three flags used above SORT_STRING, SORT_FLAG_CASE and SORT_NATURAL forces the sort function to treat the items as strings, sort in a case-insensitive way and maintain natural order respectively.

Note: Using the natcasesort() function would not be a correct answer, since it would not maintain the original index association of the elements of the array.

What is PEAR in php?

PEAR (PHP Extension and Application Repository) is a framework and repository for reusable PHP components. PEAR is a code repository containing all kinds of php code snippets and libraries.

PEAR also offers a command-line interface that can be used to automatically install packages.

What are the differences between echo and print in PHP?

echo and print are largely the same in PHP. Both are used to output data to the screen.

The only differences are as follows:

  1. echo does not return a value whereas print does return a value of 1 (this enables print to be used in expressions).
  2. echo can accept multiple parameters (although such usage is rare) while print can only take a single argument.
 

Consider the following code:

$x = NULL;

if ('0xFF' == 255) {
    $x = (int)'0xFF';
}

What will be the value of $x after this code executes? Explain your answer.

Perhaps surprisingly, the answer is neither NULL nor 255. Rather, the answer is that $x will equal 0 (zero).

Why?

First, let’s consider whether '0xFF' == 255 will evaluate to true or false. When a hex string is loosely compared to an integer, it is converted to an integer. Internally, PHP uses is_numeric_string to detect that the string contains a hex value and converts it to an integer (since the other operand is an integer). So in this case, ‘0xFF’ is converted to its integer equivalent which is 255. Since 255 = 255, this condition evaluates to true. (Note that this only works for hex strings, not for octal or binary strings.)

But if that’s the case, shouldn’t the statement $x = (int)'0xFF'; execute and result in $x being set equal to 255?

Well, the statement does execute, but it results in $x being set equal to 0, not 255 (i.e., it is not set to the integer equivalent of ‘0xFF’). The reason is that the explicit type cast of the string to an integer uses convert_to_long (which works differently than the is_numeric_string function that was used in evaluating the conditional expression, as explained above). convert_to_long processes the string one character at a time from left to right and stops at the first non-numeric character that it reaches. In the case of ‘0xFF’, the first non-numeric character is ‘x’, so the only part of the string processed is the initial ‘0’. As a result, the value returned by (int)'0xFF' is 0, so when the code completes, $x will be equal to 0.

 

What is use of the header() function in PHP?

  1. header() is used to redirect from one page to another: header("Location: index.php");
  2. header() is used to send an HTTP status code: header("HTTP/1.0 this Not Found");
  3. header() is used to send a raw HTTP header: header('Content-Type: application/json');
 

What is the difference between include_once() and require_once(), which one would you use in circumstances where you need to connect to a database, and why?

include_once() or include allows a file to be included, and in cases where the file is missing or has the wrong name, we receive an error message and execution will still continue regardless.

On the other hand, require_once() or require would be suitable in cases where a file needs to be included once and if it is missing or has a wrong name then we receive a fatal error and the execution of the program stops.

require_once or require is a suitable method in cases where a database connection file is involved and helps alleviate the possibility of multiple instances of the same file being included several times.

How can you tell if a number is even or odd without using any condition or loop?

$arr=array("0"=>"Even","1"=>"Odd");

$check=13;

echo "Your number is: ".$arr[$check%2];

What is the difference between session and quickies?

Session stores the value on the server and quickies stores the value on the user’s browser.

What does the follow code echo?

$a = "PHP";
$a = $a + 1;
echo $a;

The number 1.

$str = 'drinking giving jogging 喝 喝 passing 制图 giving 跑步 吃';  // Example input 

Highlight all the Chinese characters in red and return the string.

$str = 'drinking giving jogging 喝 喝 passing 制图 giving 跑步 吃';
$string = explode(' ', $str);
$chi = array_filter( explode('_', preg_replace(array('/[^\p{Han}?]/u', '/(\s)+/'), array('_', '$1'), $str)));
$value = array ();
foreach ($string as $s) {
           if (in_array($s, $chi)) {
               $value[] = ''.$s.'';
           } else {
               $value[] = $s;
           }
}

return (implode(' ', $value));

Write a sample of code showing the nested ternary conditional operator in PHP.

$number_class = $number == 0 ? 'blue' : ($number > 0 ? 'green' : 'red');

Here we are assigning different strings to the number_class variable based on a numeric value ($number).

What are Traits?

Traits are a mechanism that provides some of the reuse advantages of multiple inheritance in languages like PHP where multiple inheritance is not supported. Traits enable developers to reuse combinations of methods from different class hierarchies.