Flexiple Logo

Hire PHP Developers: Affordable, Dedicated PHP Experts in 72 hours

Hire PHP developers to boost your web development capabilities and accelerate project timelines. Build dynamic web applications using MySQL, Laravel, Symfony, and Zend.

Access 100+ expert PHP developers, engineers and architects from Flexiple, handpicked through a 5-hour evaluation process.

Clients rate Flexiple React.js developers 4.8 / 5 on average based on 10527 reviews.

  1. Hire Talent
  2. Developers
  3. PHP Developers

Calpurino Ceaser

Worked at:

A senior full-stack developer, Mohamed has an extensive experience of13 years in the industry. Proficient in technologies like .NET...Asenior full-stack developer, Mohamed has an extensive experience of 13years in the industry. Proficient in ....A senior full-stackdeveloper, Mohamed has an extensive experience of 13 years in theindustry. Proficient in technologies like .NET...A senior full-stackdeveloper, Mohamed has an extensive experience of 13 years in theindustry. Proficient in ....

React

MongoDB

Get access to 103 vetted profiles

100+ fast-growing companies love Flexiple!

Team work makes dreamwork. Flexiple helps companies build the best possible team by scouting and identifying the best fit.

“I’ve been pleased with Purab’s performance and work ethics. He is proactive in flagging any issues and communicates well. The time zone difference is huge but he provides a sufficient overlap. He and I work together very well and I appreciate his expertise.”

Paul Cikatricis

UX and Conversion Optimization Lead

“Flexiple has exceeded our expectations with their focus on customer satisfaction! The freelancers are brilliant at what they do and have made an immense impact. Highly recommended :)”

Henning Grimm avatar

Henning Grimm

Founder, Aquaplot

“Overall Flexiple brought in high-level of transparency with extremely quick turnarounds in the hiring process at a significantly lower cost than any alternate options we had considered.”

Kislay Shashwat avatar

Kislay Shashwat

VP Finance, CREO

“Todd and I are impressed with the candidates you've gathered. Thank you for your work so far. Thanks for sticking within our budget and helping us to find strong talent. Have loved Flexiple so far — highly entrepreneurial and autonomous talent.”

William Ross avatar

William Ross

Co-Founder, Reckit

“The cooperation with Christos was excellent. I can only give positive feedback about him. Besides his general coding, the way of writing tests and preparing documentation has enriched our team very much. It is a great added value in every team.”

Moritz Gruber avatar

Moritz Gruber

CTO, Caisy.io

“Flexiple spent a good amount of time understanding our requirements, resulting in accurate recommendations and quick ramp up by developers. We also found them to be much more affordable than other alternatives for the same level of quality.”

Narayan Vyas avatar

Narayan Vyas

Director PM, Plivo Inc

“It's been great working with Flexiple for hiring talented, hardworking folks. We needed a suitable back-end developer and got to know Ankur through Flexiple. We are very happy with his commitment and skills and will be working with Flexiple going forward as well.”

Neil Shah avatar

Neil Shah

Chief of Staff, Prodigal Tech

“Flexiple has been instrumental in helping us grow fast. Their vetting process is top notch and they were able to connect us with quality talent quickly. The team put great emphasis on matching us with folks who were a great fit not only technically but also culturally.”

Tanu V avatar

Tanu V

Founder, Power Router

“Flexiple has exceeded our expectations with their focus on customer satisfaction! The freelancers are brilliant at what they do and have made an immense impact. Highly recommended :)”

Henning Grimm avatar

Henning Grimm

Founder, Aquaplot

“Overall Flexiple brought in high-level of transparency with extremely quick turnarounds in the hiring process at a significantly lower cost than any alternate options we had considered.”

Kislay Shashwat avatar

Kislay Shashwat

VP Finance, CREO

“Todd and I are impressed with the candidates you've gathered. Thank you for your work so far. Thanks for sticking within our budget and helping us to find strong talent. Have loved Flexiple so far — highly entrepreneurial and autonomous talent.”

William Ross avatar

William Ross

Co-Founder, Reckit

“The cooperation with Christos was excellent. I can only give positive feedback about him. Besides his general coding, the way of writing tests and preparing documentation has enriched our team very much. It is a great added value in every team.”

Moritz Gruber avatar

Moritz Gruber

CTO, Caisy.io

“Flexiple spent a good amount of time understanding our requirements, resulting in accurate recommendations and quick ramp up by developers. We also found them to be much more affordable than other alternatives for the same level of quality.”

Narayan Vyas avatar

Narayan Vyas

Director PM, Plivo Inc

“It's been great working with Flexiple for hiring talented, hardworking folks. We needed a suitable back-end developer and got to know Ankur through Flexiple. We are very happy with his commitment and skills and will be working with Flexiple going forward as well.”

Neil Shah avatar

Neil Shah

Chief of Staff, Prodigal Tech

“Flexiple has been instrumental in helping us grow fast. Their vetting process is top notch and they were able to connect us with quality talent quickly. The team put great emphasis on matching us with folks who were a great fit not only technically but also culturally.”

Tanu V avatar

Tanu V

Founder, Power Router

Clients

Plivo logoCertify OS logoApna Klub logoCockroach Labs logoStarbourne Labs logo

Frequently Asked Questions

View all FAQs

What is Flexiple's process?

Our process is fairly straightforward. We understand your requirements in detail and recommend freelancers per your specific needs. You can interview the freelancers we recommend though they are already vetted by us rigorously. Once you like someone and decide to work with them, we draw up a tripartite agreement. You work directly with the freelancer, just the invoicing is done by Flexiple.

Is there a project manager assigned to manage the resources?

Our core strength is with freelance developers and designers. Though we do have senior engineers who can work as tech leads, project managers are not part of our offering.

What is Flexiple's model?

We typically work on an hourly model of upwards of US$30 per hour. For full-time longer term engagements, we can also work on a monthly model of upwards of US$5000 per month.The rates vary depending on the skill sets, experience level and location of the freelancer.

What are the payment terms?

- In the hourly model, the invoice is raised weekly/ fortnightly and is payable within 3 days of receipt of invoice.
- In the monthly model, the invoice is raised monthly and is payable within 7 days of receipt of invoice.

Are there any extras charges?

The hourly/ monthly rate shared is all-inclusive. No additional charges other than taxes are applicable.

How does Flexiple match you with the right freelancer?

Based on your requirements, we look for suitable freelancers based on:
- Tech fit: Proficiency in the tech stack you need, Recent work on stack, Work in a similar role
- Culture fit: Worked in similar team structure, Understanding of your company's industry, product stage.

11+ skills that PHP Developers at Flexiple are skilled at

PHP developers at Flexiple are skilled at MySQL, Laravel among others.

Frameworks

LaravelSymfonyZend FrameworkCodeIgniterPhalconSlimLaminasYii

CMS

WordPressDrupalJoomlaMagentoSilverStripeTYPO3Concrete5Grav

Database

MySQLMariaDBPostgreSQLSQLiteMongoDBRedis

Testing

PHPUnitBehatCodeceptionPHPSpec

Package/Dependency Managers

ComposerPackagist

Miscellaneous

HHVM (HipHop Virtual Machine)TwigBlade

How to hire the best PHP Developers?

Looking to hire PHP developers but not sure about how to hire the perfect fit? Well, according to Daxx, there are 5.5 million PHP developers across the globe as of September 2018. That's a pretty significant number, isn't it?

Finding the right developer for you in such a large number is a serious task. That's where this guide helps you out - it has everything you need to know about hiring a freelance PHP developer.

Let's introduce PHP to you

Before diving into the fundamentals of hiring a freelance PHP developer, let's delve into some interesting facts about the history of PHP.

  • Origin story: Back in 1994, Rasmus Lerdorf used CGI binaries in C language to track visits on his online resume which brought into being a widely used scripting language that we all know of as PHP which is short for PHP: Hypertext Preprocessor.
  • Widely popular: According to W3Tech’s data, PHP is used by 79% of the websites whose server-side programming language is known.
  • Used by top tech companies: Top brands like Facebook, WordPress, Slack, Flickr, Yahoo, and TED are powered by PHP.
  • Other trivia: PHP has a mascot - a big blue elephant named elePHPant. Vincent Pontier, who came up with the design said in an interview that the idea of an elephant came very naturally as he drew the PHP letters on paper and played with them a little - he noticed that they form a shape of an elephant.

Why is PHP widespread?

Two features make PHP a great choice vs. other languages. They are:

  • Easy to integrate with other technologies such as Java- does not require re-development.
  • Ability to fix errors quickly, making it easy to maintain.

Further, PHP is considered to be a comparatively easy language to learn. This attracts newbies, who can make dynamic websites with minimum programming expertise. However, this also makes hiring a great PHP developer challenging.

What are the tools used by PHP developers?

These are some of the tools used by PHP developers

1. PHP Storm

This is a paid PHP, cross-platform integrated development environment. It has a code editor for PHP, HTML, and JS with code analysis. Automated refactoring and error prevention are also present in the tool.

2. Zend Studio

Zend Studio is also an IDE developed by Zend Technologies, for PHP. It can either be used as a standalone solution for PHP development or can be used along with Zend Server as a complete solution.

3. PhpED

PhpED is another Integrated development environment made by NuSphere. It is a robust and powerful code editor for PHP and is great for debugging PHP code. The tool also has features for web deployment.

4. PHP Debug Bar

As the name suggests, this is a debugging tool for PHP. It allows for easy catching of bugs through intuitive PHP debugging components. It can also find bugs in your HTML and JS code so that your app is error.

Writing the job description to hire PHP developers

Below are some key points that we at Flexiple have learned through trial and error - a process of filtering through over 15,000 developers. You can use these points in your process to hire PHP developers.

  • Years of software development experience: Be specific about the number of years of experience needed and the technology you’re looking for. A proxy to years of experience can be the number of production-level apps worked on.
  • Expertise in particular PHP frameworks/versions: Each PHP framework has its peculiarities and nuances. While good PHP developers can pick up other frameworks, it’s a plus point to hire a developer who already has expertise in it.
  • Type of products built in the past: Based on the type of product you are trying to build - social network, SAAS product, etc. - you can prioritize certain developers over others.
  • Exposure to certain industries: Developers who have built products in certain industries will already know key aspects of laying the foundation for a great product and will be able to predict possible problems.
  • Experience working remotely: A developer with past remote work experience is an added advantage as they would have first-hand experience of everything - right from how contracts work to streamlined communication, as well as timelines and deliverables.
  • Strong communication: An essential thing to look at when hiring a freelancer is good communication skills. Since all the communication happens online, a freelancer should be able to effectively communicate to ensure a streamlined execution of all work.

Interview Questions to hire PHP developers

Now that you have made a quality JD, it can still be tricky to evaluate the skills of your applicants when you hire PHP developers. To help you with that, we have created a pool of questions that a good PHP developer should be comfortable with.

It is important to note that the ability to answer these questions doesn't imply that you have a top-quality candidate. But it definitely is a big step in that direction.

To help you navigate through these questions, we’ve categorized the interview questions in 3 parts:

A. Basic concepts: Includes all basic concepts used across languages but we've focused on their significance in PHP. This will give you an understanding of how strong their programming foundation is.

B. Advanced concepts: Includes all concepts that someone with higher expertise should know.

C. DS/Algorithm questions: To test the logical capability of the candidate.

A. Basic concepts

What are the magic methods in PHP? List 5 magic methods and explain each with an example.

Magic methods are methods that are automatically triggered in response to a particular PHP event.

To invoke any user-defined function in PHP, you need to make a function call. A magic method is special since it doesn’t require an explicit function call. It is invoked automatically when an event is triggered.

Rules of function definition of a magic method:

  • 1. The method name must begin with 2 underscores (__).
  • 2. The method should be defined inside the class.
  • 3. The method should be declared public.

PHP magic methods invoked on creating a class instance are:

__construct()

This method is called when an object is instantiated. The purpose of the construct() method is to assign some default values to object properties. In the OOPS paradigm, this is the parallel for a constructor. Typically, this should be the first thing in your class declaration. However, just like any other method, you can choose to declare it anywhere in the class body.

Example:

class Employee{
    private $name;
    private $email;

    public function __construct($name, $email)
    {
        $this->name = $name;
        $this->email = $email;
    }
}

$objEmployee = new Employee('Sam', ‘[email protected]');

In the above example, when a new employee is instantiated with name- Sam and email- [email protected], the magic method construct is called. The __construct() method assigns values passed in the arguments to the respective object properties.

__destruct()

This method is called when the object is destroyed or no longer has any references either by PHP itself or explicitly by the user. It could also be called when the script stops or is exited.

Example:

class Employee{
    private $name;
    private $email;

    public function __construct($name, $email)
    {
        $this->name = $name;
        $this->email = $email;
    }

    public function __destruct()
    {
        echo 'This will be called when the script stops.';
    }
}

$objEmployee = new Employee('Sam', ‘[email protected]');

PHP magic methods used to deal with inaccessible class members created at runtime by the concept of PHP overloading.

__get($property)

This method is called when you try to read data from inaccessible or non-existent object properties. This method helps you to get values for such dynamic object properties.

Example:

 class Employee{
    private $data = array();

    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function __get($name)
    {
        If (isset($this->data[$name])) {
            return $this->data[$name];
        }
    }
}

$objEmployee = new Employee();
echo $objEmployee>phone;            // __get is called

__set($property, $value)

This method is called when you try to set data to inaccessible or non-existent object properties. This method helps you to get values for such dynamic object properties.

Example:

class Employee{
    private $data = array();

    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function __get($name)
    {
        If (isset($this->data[$name])) {
            return $this->data[$name];
        }
    }
}

$objEmployee = new Employee();
$objEmployee>phone = '5879584623';              // __set is called
 

__isset($content)

This method is called when a call to the isset() method is made on inaccessible or non-existent object properties. In simpler terms, it is invoked automatically while checking whether a required overloaded property is set or not.

Example:

 class Employee{
    private $data = array();

    public function __isset($name)
    {
        return isset($this->data[$name]);
    }
}
$objEmployee = new Employee();
echo isset($objEmployee>phone);

What is the purpose of $GLOBALS & $_SERVER variables in PHP?

$GLOBALS & $_SERVER variables are PHP superglobals. Superglobals are specially-defined array variables used to get or store information from the different pages of an application. These variables can be accessed at all times regardless of scope from any function, class, or file.

PHP has 3 variable scopes - local, global, and static.

  • Local - Any variable defined inside a function has a local scope and can only be accessed inside the function.
  • Global - A variable declared outside the function has a global scope and can be accessed outside the function, But, using the 'global' keyword, you can access any global variable inside a function.
  • Static - PHP deletes all variables after the function is executed. The variable must be declared static if its value needs to be used after function execution.

Example: of accessing a global variable inside a function:

$x = 10;  //global scope
$y = 12;
       function add() {
          global $x, $y;
          $y = $x + $y;
       }
addt();
echo $y;        // outputs 22

Another way of doing the same would be using the $GLOBALS superglobal.

$GLOBALS is used to access global variables from anywhere in the script. PHP stores all the global variables in an array called $GLOBALS[]. To access a particular global variable you must pass the variable name as an index to the array. ($GLOBALS[index~name])

Considering the same example:

$x = 10;
$y = 12;
function multiply(){
    $GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];
}
multiply();
echo $z; 

In the code above, $x and $y are global variables holding values 10 and 12 respectively. A function multiply() performs a multiplication operation on the two global variables using the $GLOBALS[] to output 120.

The $_SERVER superglobal stores information about the headers, paths, and script locations.

Some important elements that the $_SERVER variable holds are:

1. $_SERVER['PHP_SELF']- returns the filename of the current script

2. $_SERVER['GATEWAY_INTERFACE']- returns the CGI version

3. $_SERVER['SERVER_ADDR']- returns the host server’s IP address

4. $_SERVER['SERVER_NAME']- returns the host server name

5. $_SERVER['REQUEST_METHOD']- returns the request method used. Example- POST or GET.

6. $_SERVER['REQUEST_TIME']- returns the request start time in timestamp

7. $_SERVER['HTTP_HOST']- returns the host header of  the current request

8. $_SERVER['SCRIPT_NAME']- returns the path of the current script

9. $_SERVER['SERVER_PORT']- returns the port being used for communication

10. $_SERVER['REMOTE_ADDR']- returns the IP address of the user viewing the current page

Example:

echo $_SERVER['SERVER_NAME'];
echo $_SERVER['SCRIPT_NAME'];
The output for the above code snippet is :
localhost
/demodoc/demo_global_server.php 

What are the methods used to collect form data after the form is submitted to the server in PHP? Can you submit a form without a submit button? If yes, give 2 examples and also mention how would you verify if the form is successfully submitted?

The GET and POST methods are used to collect form data after the form is submitted to the server. They’re both treated as superglobals and hence are accessible at all times($_GET & $_POST). Both, GET and POST create an array that holds key/value pairs, where the key is the name of the form control and value is the input data from the user.

The basic difference between the two is that the $_GET variables are passed to the current script via URL parameters and $_POST variables are passed via the HTTP POST method.

The GET method is not advised when you need to send important information like a password because the information sent via the GET method is visible to everyone as opposed to that of the POST method that goes via the headers of the HTTP POST method and remains invisible to others.

The POST method has no limits on the characters passed but the GET method is limited to approximately 2000 characters only. Here’s an example of a simple form using the post method:

When the submit button is clicked, the data inside name and email input fields are sent via the HTTP POST method to a PHP file.

Hi <?php echo $_POST["name"]; ?>Your email address is: <?php echo $_POST["email"]; >
The output of the above snippet will be:
Welcome Sam
Your email address is: [email protected]
To achieve the same with $_GET, change the method to ‘get’:
<form action="reg.php" method="get">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
#reg.php
Hi <?php echo $_GET["name"]; ?>
Your email address is <?php echo $_GET["email"]; ?>
The output then be:
Hi Sam
Your email address is [email protected].
And the URL will be
localhost/reg.php?name=Sam&email=sam%robustplus.com
Yes, a form can be submitted without the submit button. The most commonly used ways of doing it are: A. Submit a form by clicking on a link using the onclick() method:
<a href="#" onclick="document.getElementById('submit').submit(); >
where 'submit' is the form ID. B. Submit by selecting an option from the drop-down menu on change:
$('#theme').change(function(){
$('form').submit();
});
where ‘theme’ is the id of <select> The isset() method is used to check if the form has been successfully submitted.
if (isset($_POST['submit'])) {
    echo "Successful submission";
}
where ‘submit’ is the button name.

B. Advanced concepts

What are traits in PHP? What are the keywords used to declare and use traits? Explain with an example.

PHP doesn’t support multiple inheritances. The ‘extends’ keyword is used to perform a single class inheritance. Traits were introduced in PHP 5.4 to provide multiple inheritances. In a nutshell, traits are used to declare methods that can be used in multiple classes. These methods also include abstract methods with any access modifier- public, private, or protected.

Traits are similar to classes but they are used for grouping methods consistently and unlike a class, they can’t be instantiated on their own.

The 'trait’ keyword is used to declare traits:

trait Trait1{
  //code
}

And the use’ keyword is used to use a trait in a class:

class MyClass {
use Trait1;
}

Example:

Let’s create a library.php file and create a class library

class Library{
     public function student(){
          echo "I am student A";
      }
}

Now, let’s create another file index.php and create a class book and extend it to Library

require_once 'Library.php';
class Book extends Library{
}
$obj = new Book;
$obj->student();

When we run index.php it will output ‘I am student A’ but what if Book comes with a new feature of having an ebook version? Let’s create a new file for ebook.php

class Ebook{
   public function version(){
     echo '1.0’;
   }
}

Now, if I want to inherit Book in the index.php file- I can’t do it because it already extends Library.

This is where I can use traits. All I have to do is convert the class to a trait like:

trait Ebook{
 public function version(){
   echo '1.0’;
  }
}

Now to make the methods in Ebook available in Index- I need to add ebook in index.php>

require_once ‘Library.php';
require_once ‘Ebook.php';
   class Book extends Library{
     use Ebook;
    }
$obj = new Book;
// now I can use methods inside trait Ebook
$obj->version();
//and methods from library
$obj->student();

I can also use 2 traits together. Let's assume I have another trait Price with a function range.

Index.php:

require_once ‘Library.php';
require_once ‘Ebook.php'; 
require_once ‘Price.php'; 

   class Book extends Library{ 
       use Ebook, Price; 
   } 
$obj = new Book;
// now I can use methods inside trait Price
$obj->range(); 
// now I can use methods inside trait Ebook
$obj->version(); 
// and method from Library
$obj->student();

If you have 2 traits with the same method name range. PHP will throw a fatal error but it can be fixed using the ‘insteadof’ keyword.

Ebook::range insteadof Price;
//Or pass it as an alias:
Price::range as Prange; 

How are objects created in PHP? Why and how are the keywords $this and $instancof used? Explain with examples.

Objects are individual instances of the data structure defined by a class. We can make multiple objects from a class. Each object inherits all the properties and methods defined in the class but has different property values.

Objects of a class are created using the new keyword.

Example:

class Colors{}
$yellow = new Colors;
$orange = new Colors; 

Objects are also called instances. Once you’ve created the objects, you can use parent class methods on them.

class Colors{
function set_name($name) {
    $this->name = $name;
  }
function get_name() {
    return $this->name;
  }
}
$yellow = new Colors;
$yellow>set_name('light');
echo $yellow>get_name();

The $this keyword maps to the current object and allows you to make changes to object values inside the method.

Example:

class Colors{ public $shade; }
$yellow = new Colors;

If I want to change the value of $shade, I can create a method set_shade() and use the $this keyword inside the class like:

class Colors{
  public $shade;
      function set_shade($name) {
         $this->shade = $shade;
       }
   }
$yellow = new Colors();
$yellow>set_shade("Light Yellow");

Or I can do it outside the class directly:

class Colors{
  public $shade;
}
$yellow = new Colors();
$yellow>shade = "Light Yellow";

The $instanceof keyword is used to check if an object belongs to a specific class.

Example:

$yellow = new Colors();
var_dump($yellow instanceof Colors);
The output will be bool(true). 

What are the types of arrays supported in PHP? What is an array filter? List 3 different ways of sorting arrays in PHP.

An array is a data structure that can hold many values of similar data types under a single name. Individual array values are accessed via an array index which starts with 0.

PHP supports 3 types of arrays:

1. Indexed arrays have a numeric index and the stored values are accessed linearly.

Example: To store values:

$colors = array("Red", "Yellow", "Oange"); 

To access the stored values:

echo "I like " . $colors[0] . ", " . $colors[1] . " and " . $colors[2] . "."; 

2. Associative arrays have strings indexes. Array values are stored in key-value pairs.

Example: To store values:

$rgb = array("R"=>"35", "G"=>"37", "B"=>"43"); 

To access the stored values:

echo "The R-value is " . $rgb[R] ;

3. A multidimensional array is an array of arrays. The dimension of an array indicates the number of indices needed to map an element. For example, a two-dimensional array needs two indices to select an element, a three-dimensional array needs three, and so on.

Example of a two-dimensional array: Consider we are storing the age and job experience in years for every candidate.

The declaration will look something like this:

$candidate = array (
  array("A",22,2),
  array("B",15,3),
  array("C",5,1)
);

And to access the information stored for candidate B,

echo $candidate[1][0].": Age: ".$candidate[1][1].", Experience: ".$candidate[1][2].".";

array_filter() is a built-in PHP function to filter the elements of an array using a callback function. array_filter() iterates through each value in the array and passes it to the callback function. If the callback function returns true, the current array value is returned else preserved.

Syntax: array array_filter($array(mandatory), $callback_function(optional), $flag(optional))

Parameters:

1. $array-> refers to the input array which needs to be filtered

2. $callback_function-> refers to the user-defined function. If none is passed, all values equal to FALSE are removed from the input array.

3. $flag-> refers to the arguments passed in the callback function.

Returns a filtered array.

Example: to get even numbers :

function Even($array)
{
    if($array%2==0)
        return TRUE;
    else
        return FALSE;
}
$array = array(12, 0, 1, 18, 25, 0, 46);
print_r(array_filter($array, "Even"));
Output: Array
(
    [0] => 12
    [1] => 0
    [2] => 18
    [3] => 0
    [5] => 46
)

3 ways to sort arrays in PHP are:

1. sort() - sorting the input array in ascending order

Example:

$colors = array("Red", "Yellow", "Oange"); 
sort($colors); 
Output- Orange Red Yellow 

2. rsort() - sorting the input array in descending order

Example:

$colors = array("Red", "Yellow", "Oange"); 
sort($colors);
Output- Yellow Red Orange

3. asort() - sort associative arrays in ascending order, according to the value.

Example:

$age = array("C"=>"20", "B"=>"07", "J"=>"43"); 
asort($age);
Output:
Key=B, Value=07
Key=C, Value=20
Key=J, Value=43 

What are generators and how are they different from normal functions? How do they work in PHP? Can you send values to the generator? If yes, how? Explain with an example.

Generators were introduced in PHP 5.5 and while they look like functions, they act like iterators. Generators nullify the complexity of implementing a class that implements the Iterator interface. They are similar to functions except that they don’t return a value but yield as many values as needed.

Generators return an object that can be iterated over. This is an object of the internal Generator class that implements the Iterator interface. Generators use the keyword ‘yield’ instead of ‘return’. Unlike ‘return’, ‘yield’ does not remove the function from the stack- it rather saves its state so that the execution can be continued when it is called again. Although, the ‘return’ keyword can be used to terminate the execution. The main purpose of a generator is to save memory and speed up the execution.

Example:

function read_file($filename) {
    $file = fopen($filename, 'r');
    while (($line = fgets($file)) !== false) {
        yield $line;
    }
    fclose($file);
}
foreach (read_file(‘file_name’) as $line) {
}

In the above code, the generator function yields the lines of the file passed as and when needed. Each time a call is made, the generator resumes from where it left off. After all the lines are read, the generator terminates and the loop ends.

Yes, the send() method is used to send values or commands to the generator. This method is used on the result of the yield expression. For example, telling the generator to stop the execution.

Example:

function numbers() {
    for ($i = 0; $i < 6; ++$i) {
        $cmd = (yield $i);
        if ($cmd == 'stop') {
        return; // exit the generator
        }
    }
}
$generator = numbers();
foreach ($generator as $a) {
    if ($a == 4) {
        $generator->send('stop');
    }
    echo "{$a}";
}
In the above code, the generator will iterate till a is 4, output- 0 1 2 3 4 and terminate the execution. 

What is composition over inheritance? Where does PHP (as a language) implement this?

Composition over inheritance in OOP is the principle that classes should achieve polymorphism by their composition (reusing code) rather than inheritance from a base or parent class.

In OOP, there are two ways of achieving polymorphism- inheritance & composition.

Inheritance is based on a parent-child relationship a.k.a the ‘Is-a’ relationship. It bases one class/object on another class/object retaining similar implementation. In simpler words, a subclass inherits all methods of its superclass. For example, a subclass ‘Cat’ inherits all traits of its superclass ‘Animal’.

Composition, on the other hand, is the mechanism to reuse code across classes. The superclass is connected to the subclasses via a ‘has-a’ relationship. For example, a class ‘Car’ can be composed of an ‘Engine’ class as well as any other components to achieve a holistic functioning of the ‘Car’ class.

While Composition is dynamic binding (run-time binding), Inheritance is static binding (-binding)

To explain with an example composition over inheritance,

class Vehicle
{
    public function move()
    {
        echo "Move the car";
    }
}
class Car extends Vehicle
{
    public function accelarate()
    {
     move();
    }
$car = new Car();
$car->accelerate();
}

In the above code snippet, there is a tight coupling(inheritance) between the classes- Vehicle and Car. Even the slightest change in the move() function in Vehicle class will cause the class Car to break. This can be solved using composition:

class Vehicle
{ 
    public function move() 
    { 
        echo "Move the car"; 
    } 
} 
class Car 
{ 
    private $vehicle; 
    public function __construct(Vehicle $vehicle)
    { 
        $this->vehicle = $vehicle; 
    } 
    public function accelarate() 
    { 
        $this->vehicle->move(); 
    } 
} 
$vehicle = new Vehicle(); 
$car = new Car($vehicle); 
$car->accelarate();

In this code snippet, passing the reference of class Vehicle into class Car’s constructor using dependency injection removes the tight coupling. The superclass and subclass are now independent of each other.

What is the factory pattern? How would you implement it in PHP?

Design patterns in PHP act like blueprints that can be customized to solve a recurring software design problem. These patterns provide well tested, proven development/design paradigms that help to speed up the development process. Using design patterns, you can make your code more reusable, flexible, and maintainable.

PHP has 3 design patterns-

1. Creational patterns: These patterns are used to construct objects that can be decoupled from their implementing system.

2. Structural patterns: These patterns are used to form object structures between many different objects

3. Behavioral patterns: These patterns are used to manage relationships, algorithms, and responsibilities between objects.

The Factory design pattern is one of the most used creational design patterns. It solves the problem of creating product objects without specifying their concrete class by maintaining a dedicated class responsible only for making objects. It is recommended to use the factory pattern when the subclass of an object instantiated can vary.

Example:

class Digital
{
    private $mobileMake;
    private $mobileModel;
    public function __construct($make, $model)
    {
        $this->mobileMake = $make;
        $this->mobileModel = $model;
    }
    public function getMakeAndModel()
    {
        return $this->mobileMake . ' ' . $this->mobileModel;
    }
}
class DigitalFactory
{
    public static function create($make, $model)
    {
        return new Digital($make, $model);
    }
}

$honor = DigitalFactory::create('Honor', '10 Lite');
print_r($honor>getMakeAndModel()); // outputs "Honor 10 Lite"

This code uses a 'DigitalFactory' to create a Digital object. The 2 benefits of doing this are:

1. You can change, rename, or replace the Digital class whenever you need to- all you have to do is modify the code in the 'DigitalFactory', instead of every instance of the class in your project.

2. Instead of creating a new instance every time you want to create an object- you can simply do all the work in the factory and reuse it.

C. Data Structure/ Algorithm

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.

function hasMatchedParenthesis($string) {
        $len = strlen($string);
        $string_check = 1;
        $stack = [];
        for ($i = 0; $i < $len; $i++) {
            switch ($string[$i]) {
                case '(': array_push($stack, 0); 
                break;
                case ')':
                    if (array_pop($stack) !== 0)
                        return 0;
                break;
                case '[': array_push($stack, 1); 
                break;
                case ']':
                    if (array_pop($stack) !== 1)
                        return 0;
                break;
                case '{': array_push($stack, 1); break;
                case '}':
                    if (array_pop($stack) !== 1)
                        return 0;
                break;
                default:
                       $string_check = 0 ;
                break;
            }
        }
        return ($string_check ? empty($stack) : 0);
}

$result = hasMatchedParenthesis(")("); 
echo $result;
The above code will Output 0 (False). 

What will the output of the following code be?

$x = 10;
$y = 5;
$z = 3;
if ($x / $y / $z)
    print "hi";
else
    print "hello"; 
a) hi b) hello c) error d) no output
The answer is A because the floating-point division in PHP returns a non zero value = 0.66 which evaluates to
true and outputs ‘hi’.

What will the output of the following code be?

$x = 2
$y = 4
$z = 6
if($z > $y > $x) {
    echo “true”;
}else{
    echo “false”;
}
The answer is False. It may look like the output can be true because 6 > 4 > 2 is true but PHP evaluates
$z > $y first which returns a boolean value of 1 or true. This value (true or 1) is compared to the next integer
in the chain, bool(1) > $z, which will result in NULL and echo “false.” 

Hire PHP developers - parting thoughts

Now that you know what to look for in a candidate when hiring a freelance PHP developer, the question is where to find these freelance developers? If you've been in the freelance industry for a while- you've probably heard of Toptal and are aware that it could be a little heavy on your pockets.

You can find the best freelance PHP developers at Flexiple. Flexiple has already served over a hundred clients, earning great reviews for the quality of service but if you’re still not convinced- here are some reasons why you should consider Flexiple. You can also take a look at our detailed article about the top alternatives for Toptal and pick one that suits you best.

And there you have it- that's everything you need to know about hiring a freelance PHP developer. To quickly summarize it for you:

  • Note your project requirements and hire accordingly. Do not go for the lowest or the highest-paid developer.
  • Don’t hire without vetting- consider asking questions right from the basics to advanced to logical questions.
  • Look for companies like Flexiple that help you find the perfect fit.

That's about all you need to know to hire PHP developers. Happy hiring! :)

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.