PHP Tutorial

Php advanced, mysql database, php examples, php reference, php exercises.

You can test your PHP skills with W3Schools' Exercises.

We have gathered a variety of PHP exercises (with answers) for each PHP Chapter.

Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start PHP Exercises

Start PHP Exercises ❯

If you don't know PHP, we suggest that you read our PHP Tutorial from scratch.

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Tutorials Class - Logo

  • PHP All Exercises & Assignments

Practice your PHP skills using PHP Exercises & Assignments. Tutorials Class provides you exercises on PHP basics, variables, operators, loops, forms, and database.

Once you learn PHP, it is important to practice to understand PHP concepts. This will also help you with preparing for PHP Interview Questions.

Here, you will find a list of PHP programs, along with problem description and solution. These programs can also be used as assignments for PHP students.

Write a program to count 5 to 15 using PHP loop

Description: Write a Program to display count, from 5 to 15 using PHP loop as given below.

Rules & Hint

  • You can use “for” or “while” loop
  • You can use variable to initialize count
  • You can use html tag for line break

View Solution/Program

5 6 7 8 9 10 11 12 13 14 15

Write a program to print “Hello World” using echo

Description: Write a program to print “Hello World” using echo only?

Conditions:

  • You can not use any variable.

View Solution /Program

Hello World

Write a program to print “Hello PHP” using variable

Description: Write a program to print “Hello PHP” using php variable?

  • You can not use text directly in echo but can use variable.

Write a program to print a string using echo+variable.

Description: Write a program to print “Welcome to the PHP World” using some part of the text in variable & some part directly in echo.

  • You have to use a variable that contains string “PHP World”.

Welcome to the PHP World

Write a program to print two variables in single echo

Description: Write a program to print 2 php variables using single echo statement.

  • First variable have text “Good Morning.”
  • Second variable have text “Have a nice day!”
  • Your output should be “Good morning. Have a nice day!”
  • You are allowed to use only one echo statement in this program.

Good Morning. Have a nice day!

Write a program to check student grade based on marks

Description:.

Write a program to check student grade based on the marks using if-else statement.

  • If marks are 60% or more, grade will be First Division.
  • If marks between 45% to 59%, grade will be Second Division.
  • If marks between 33% to 44%, grade will be Third Division.
  • If marks are less than 33%, student will be Fail.

Click to View Solution/Program

Third Division

Write a program to show day of the week using switch

Write a program to show day of the week (for example: Monday) based on numbers using switch/case statements.

  • You can pass 1 to 7 number in switch
  • Day 1 will be considered as Monday
  • If number is not between 1 to 7, show invalid number in default

It is Friday!

Write a factorial program using for loop in php

Write a program to calculate factorial of a number using for loop in php.

The factorial of 3 is 6

Factorial program in PHP using recursive function

Exercise Description: Write a PHP program to find factorial of a number using recursive function .

What is Recursive Function?

  • A recursive function is a function that calls itself.

Write a program to create Chess board in PHP using for loop

Write a PHP program using nested for loop that creates a chess board.

  • You can use html table having width=”400px” and take “30px” as cell height and width for check boxes.

Chess-board-in-PHP-using-for-loop

Write a Program to create given pattern with * using for loop

Description: Write a Program to create following pattern using for loops:

  • You can use for or while loop
  • You can use multiple (nested) loop to draw above pattern

View Solution/Program using two for loops

* ** *** **** ***** ****** ******* ********

Simple Tips for PHP Beginners

When a beginner start PHP programming, he often gets some syntax errors. Sometimes these are small errors but takes a lot of time to fix. This happens when we are not familiar with the basic syntax and do small mistakes in programs. These mistakes can be avoided if you practice more and taking care of small things.

I would like to say that it is never a good idea to become smart and start copying. This will save your time but you would not be able to understand PHP syntax. Rather, Type your program and get friendly with PHP code.

Follow Simple Tips for PHP Beginners to avoid errors in Programming

  • Start with simple & small programs.
  • Type your PHP program code manually. Do not just Copy Paste.
  • Always create a new file for new code and keep backup of old files. This will make it easy to find old programs when needed.
  • Keep your PHP files in organized folders rather than keeping all files in same folder.
  • Use meaningful names for PHP files or folders. Some examples are: “ variable-test.php “, “ loops.php ” etc. Do not just use “ abc.php “, “ 123.php ” or “ sample.php “
  • Avoid space between file or folder names. Use hyphens (-) instead.
  • Use lower case letters for file or folder names. This will help you make a consistent code

These points are not mandatory but they help you to make consistent and understandable code. Once you practice this for 20 to 30 PHP programs, you can go further with more standards.

The PHP Standard Recommendation (PSR) is a PHP specification published by the PHP Framework Interop Group.

Experiment with Basic PHP Syntax Errors

When you start PHP Programming, you may face some programming errors. These errors stops your program execution. Sometimes you quickly find your solutions while sometimes it may take long time even if there is small mistake. It is important to get familiar with Basic PHP Syntax Errors

Basic Syntax errors occurs when we do not write PHP Code correctly. We cannot avoid all those errors but we can learn from them.

Here is a working PHP Code example to output a simple line.

Output: Hello World!

It is better to experiment with PHP Basic code and see what errors happens.

  • Remove semicolon from the end of second line and see what error occurs
  • Remove double quote from “Hello World!” what error occurs
  • Remove PHP ending statement “?>” error occurs
  • Use “
  • Try some space between “

Try above changes one at a time and see error. Observe What you did and what error happens.

Take care of the line number mentioned in error message. It will give you hint about the place where there is some mistake in the code.

Read Carefully Error message. Once you will understand the meaning of these basic error messages, you will be able to fix them later on easily.

Note: Most of the time error can be found in previous line instead of actual mentioned line. For example: If your program miss semicolon in line number 6, it will show error in line number 7.

Using phpinfo() – Display PHP Configuration & Modules

phpinfo()   is a PHP built-in function used to display information about PHP’s configuration settings and modules.

When we install PHP, there are many additional modules also get installed. Most of them are enabled and some are disabled. These modules or extensions enhance PHP functionality. For example, the date-time extension provides some ready-made function related to date and time formatting. MySQL modules are integrated to deal with PHP Connections.

It is good to take a look on those extensions. Simply use

phpinfo() function as given below.

Example Using phpinfo() function

Using-phpinfo-Display-PHP-Configuration-Modules

Write a PHP program to add two numbers

Write a program to perform sum or addition of two numbers in PHP programming. You can use PHP Variables and Operators

PHP Program to add two numbers:

Write a program to calculate electricity bill in php.

You need to write a PHP program to calculate electricity bill using if-else conditions.

  • For first 50 units – Rs. 3.50/unit
  • For next 100 units – Rs. 4.00/unit
  • For next 100 units – Rs. 5.20/unit
  • For units above 250 – Rs. 6.50/unit
  • You can use conditional statements .

problem solving with php

Write a simple calculator program in PHP using switch case

You need to write a simple calculator program in PHP using switch case.

Operations:

  • Subtraction
  • Multiplication

simple-calculator-program-in-PHP-using-switch-case

Remove specific element by value from an array in PHP?

You need to write a program in PHP to remove specific element by value from an array using PHP program.

Instructions:

  • Take an array with list of month names.
  • Take a variable with the name of value to be deleted.
  • You can use PHP array functions or foreach loop.

Solution 1: Using array_search()

With the help of  array_search()  function, we can remove specific elements from an array.

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=> string(3) “may” }

Solution 2: Using  foreach()

By using  foreach()  loop, we can also remove specific elements from an array.

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=> string(3) “may” }

Solution 3: Using array_diff()

With the help of  array_diff()  function, we also can remove specific elements from an array.

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [2]=> string(5) “march” [4]=> string(3) “may” }

Write a PHP program to check if a person is eligible to vote

Write a PHP program to check if a person is eligible to vote or not.

  • Minimum age required for vote is 18.
  • You can use PHP Functions .
  • You can use Decision Making Statements .

Click to View Solution/Program.

You Are Eligible For Vote

Write a PHP program to calculate area of rectangle

Write a PHP program to calculate area of rectangle by using PHP Function.

  • You must use a PHP Function .
  • There should be two arguments i.e. length & width.

View Solution/Program.

Area Of Rectangle with length 2 & width 4 is 8 .

  • Next »
  • PHP Exercises Categories
  • PHP Top Exercises
  • PHP Variables
  • PHP Decision Making
  • PHP Functions
  • PHP Operators

Uploaded avatar of dstockto

Want to learn and master PHP?

Join Exercism’s PHP Track for access to 114 exercises grouped into 11 PHP Concepts, with automatic analysis of your code and personal mentoring , all 100% free.

114 coding exercises for PHP on Exercism. From Transpose to Pig Latin.

Get better at programming through fun, rewarding coding exercises that test your understanding of concepts with Exercism.

Take input text and output it transposed.

Given a string representing a matrix of numbers, return the rows and columns of that matrix.

Implement a program that translates from English to Pig Latin

problem solving with php

Key Features of PHP

PHP is constantly being updated and improved.

Web Focused

PHP was designed specifically with web development in mind.

As a general purpose scripting language, PHP can be used for almost any task.

PHP's simple syntax, gradual typing, and robust standard library make rapid development a breeze.

Well Documented

PHP is well documented by the official PHP.net website, which includes helpful community commentary.

Cross-platform

Write once, run anywhere PHP is supported.

A taste of the concepts you'll cover

Get mentored the php way.

Every language has its own way of doing things. PHP is no different. Our mentors will help you learn to think like a PHP developer and how to write idiomatic code in PHP. Once you've solved an exercise, submit it to our volunteer team, and they'll give you hints, ideas, and feedback on how to make it feel more like what you'd normally see in PHP - they'll help you discover the things you don't know that you don't know.

Community-sourced PHP exercises

The PHP track on Exercism has 11 concepts and 114 exercises to help you write better code. Discover new exercises as you progress and get engrossed in learning new concepts and improving the way you currently write.

Get started with the PHP track

The best part, it’s 100% free for everyone.

8 PHP Interview Questions Every Developer Should Know

HackerRank AI Promotion

The world of software development evolves at a dizzying pace. Yet it is the oldest programming languages that continue to make the biggest impact. One such language that has consistently held its ground is PHP . Created in 1994 , it’s the backbone of 77.4 percent of all websites with a known server-side programming language, highlighting its profound influence on the internet’s infrastructure. 

This widespread usage of PHP in various domains opens up a world of opportunities, leading to a growing demand for proficient PHP developers. However, with high demand comes high standards. Companies are on the lookout for professionals who can tackle complex problems, write efficient code, and effectively manage and manipulate data. Understanding the nuances of PHP, therefore, becomes a valuable skill, both for developers seeking to showcase their PHP prowess and for recruiters intent on hiring the best talent.

This post will dive into some PHP essentials and guide you through a series of progressively challenging PHP interview questions, providing illustrative code snippets and clear explanations to help you tackle your next PHP interview with confidence.

What is PHP?

PHP , an acronym for “Hypertext Preprocessor”, is a widely-used, open-source scripting language. It was specially designed for web development but is also used as a general-purpose programming language. PHP scripts are primarily used on the server side, meaning they run on the web server. It’s a robust platform for creating dynamic and interactive websites and web applications, which is part of what makes it so prevalent across the web.

The beauty of PHP lies in its flexibility. It can be embedded directly within HTML code, eliminating the need for calling an external file to process data. It also integrates seamlessly with various databases such as MySQL, Oracle, and Microsoft SQL Server. Plus, it’s compatible with most web servers and runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.), providing developers with extensive versatility.

Given its server-side scripting prowess, PHP is typically used to perform operations like form data collection, file handling on the server, session tracking, or even building entire e-commerce websites. This wide range of applications explains why PHP skills are sought after for various technical roles.

What a PHP Interview Looks Like

The PHP interview process varies between organizations, but a few constants provide a broad picture of what to expect. These interviews are designed to assess a candidate’s understanding of PHP as a language, its applications, problem-solving skills, and sometimes their experience with PHP-based frameworks like Laravel or Symfony .

One of the first things to note is that PHP interviews often involve several layers. Typically, there’s an initial screening to evaluate the candidate’s basic PHP knowledge and possibly some related technologies like SQL or JavaScript . Following that, there’s usually a technical interview that delves deeper into PHP concepts and problem-solving skills .

A significant component of the technical interview is the coding challenge. These challenges test the ability of a candidate to apply their knowledge to solve real-world problems. They can range from simple tasks like string manipulation to more complex problems such as creating a simple CRUD (Create, Retrieve, Update, Delete) application or working with APIs.

The type of roles that require PHP skills vary widely but most commonly include web development roles. Web developers, particularly back-end developers , are often expected to have a solid understanding of PHP to create dynamic web pages or web applications. Other roles like software engineers might also need to know PHP, especially if they’re working on web-based applications. 

Even certain database administrator roles might require PHP knowledge, as PHP is commonly used to interact with databases. Additionally, since PHP can be used as a general-purpose scripting language, it could also come in handy for system administrators.

PHP Interview Questions

The complexity and depth of PHP interview questions can range widely, depending on the specific role and level of expertise required. This section will explore a progressive series of PHP coding challenges that span intermediate to advanced proficiency. These questions will serve as a vital resource for developers seeking to sharpen their skills or for hiring teams aiming to evaluate candidate competencies effectively.

1. Array Manipulation

Task: Write a PHP function called findMissingNumber that takes an array of consecutive numbers as input and returns the missing number.

Input Format: The input will be an array of integers.

Constraints:

  • The array will contain consecutive integers, with one integer missing.
  • The array will have at least two elements.

Output Format: The output will be an integer.

Sample Input: [1, 2, 4, 5, 6]

Sample Output: 3

Sample Code:

Explanation: 

The function first calculates the total sum of what the numbers would be if none were missing. Then it calculates the sum of the given numbers. The difference between these two sums is the missing number. This question tests the candidate’s ability to use built-in PHP functions for array manipulation and mathematical computations.

2. Handling Exceptions and Working with Files

Task: Write a PHP function called readFileAndSumNumbers that reads a file with numbers (one number per line), parses the numbers, and returns their sum.

Input Format: The input will be a string representing the path to the file.

  • The file will contain at least one number.
  • The file may contain empty lines or lines with non-numeric characters.
  • Each number will be an integer.

Output Format: The output will be an integer representing the sum of all numbers in the file. If a line cannot be parsed as a number, it should be ignored.

Sample Input: “numbers.txt” (file content: 1\n2\n3\nfoo\n4\n5\nbar\n)

Sample Output: 15

Explanation:

The readFileAndSumNumbers function starts by defining a sum variable to hold the total sum of the numbers. It then attempts to read each line from the file.

The is_numeric() function is used to check if each line can be treated as a number. If it can, the line is cast to an integer and added to the sum. If not, the line is ignored.

If an exception occurs during the execution of the code (such as a RuntimeException if the specified file doesn’t exist), the exception is caught and an error message is printed. Regardless, the function returns the sum of the parsed numbers.

This question tests a candidate’s ability to handle exceptions and work with files in PHP. It also provides an opportunity to demonstrate understanding of PHP’s type checking and casting mechanisms.

3. Regular Expressions

Task: Write a PHP function called isValidEmail that takes a string as input and uses a regular expression to verify if it is a valid email address. 

Input Format: The input will be a string.

Constraints: The string will contain at least one character.

Output Format: The output will be a boolean. Return true if the string is a valid email address and false otherwise.

Sample Input: [email protected]

Sample Output: true

The isValidEmail function uses PHP’s built-in filter_var function with the FILTER_VALIDATE_EMAIL filter to validate the email address. If the email is valid, the function returns true ; if it’s not, it returns false .

This question tests a candidate’s understanding of PHP’s built-in functions and ability to handle string validation tasks that are common in real-world applications.

4. Object-Oriented Programming

Task: Define a PHP class called Circle , with a private property radius . Add a constructor to set the radius and two public methods: getArea and getCircumference to calculate the area and the circumference of the circle, respectively.

The Circle class is defined with a private property radius . The constructor method takes radius as a parameter and assigns it to the radius property. 

Two public methods, getArea and getCircumference , are defined to calculate the area and circumference of the circle. They use the pi() function to get the value of π, and pow() to calculate the square of the radius. 

This question tests a candidate’s understanding of object-oriented programming concepts in PHP, such as classes, properties, methods, and constructors.

Explore verified tech roles & skills.

The definitive directory of tech roles, backed by machine learning and skills intelligence.

Explore all roles

5. Dealing with Databases

Task: Write a PHP function called fetchUsers that connects to a MySQL database, fetches all records from the users table, and returns the result as an array.

The fetchUsers function first creates a new MySQLi object and establishes a connection with the MySQL database using the provided hostname, username, password, and database name. 

It then constructs a SQL query to fetch all records from the users table. The query is executed using the query() method of the MySQLi object. 

The function iterates over the result set using a while loop and the fetch_assoc() method, which fetches a result row as an associative array. Each row is added to the users array. 

Once all rows have been fetched, the database connection is closed using the close() method of the MySQLi object. 

This question tests the candidate’s understanding of PHP’s MySQLi extension, which allows PHP to access and manipulate MySQL databases, and their ability to interact with databases using SQL.

6. Design Patterns

Task: Implement a Singleton design pattern in PHP.

The Singleton class is a design pattern that restricts a class from instantiating multiple objects. It’s useful when only a single instance of a class is required to control actions. 

It’s implemented by creating a class with a method that creates a new instance of the class if one doesn’t exist. If an instance already exists, it simply returns a reference to that object. To prevent additional instantiation, the constructor is made private.

In the provided sample code, Singleton is a class with a private static variable $instance to hold the single instance of the class, a private constructor to prevent external instantiation, and a public static getInstance method to control the access to the single instance of the class.

This question tests a candidate’s understanding of design patterns in PHP, specifically the Singleton pattern. It requires a good understanding of object-oriented programming principles in PHP, including classes, methods, and variables visibility (public, private, protected), and static properties and methods.

7. Memory Management

Task: Write a PHP function called calculateMemoryUsage that takes a large array as an input, performs a certain operation on the array (like sorting it), and then calculates and returns the difference in memory usage before and after the operation.

The calculateMemoryUsage function uses PHP’s memory_get_usage function to get the amount of memory, in bytes, that’s currently being used by the PHP script. 

It captures the memory usage at the start, performs an operation (in this case, sorting the array), and then captures the memory usage again at the end. The difference between the end and start memory usages is calculated and returned, representing the additional memory used by the operation.

This question is a good opportunity for candidates to demonstrate an understanding of how PHP manages memory and the impact of different operations on memory usage. It’s an important consideration for writing efficient, performant PHP code, especially when dealing with large data sets.

8. HTTP and Session Management

Task: Write a PHP script to start a new session, set a session variable, and then retrieve the value of that session variable.

In this task, the PHP session_start function is first called to start a new session or to resume the current one. This is necessary before any session variables can be set.

Then, a session variable “favorite_color” is set to “blue” using the global $_SESSION variable, which is an associative array containing session variables available to the current script.

Finally, the value of the “favorite_color” session variable is retrieved and stored in the $favoriteColor variable.

This question tests a candidate’s understanding of HTTP, sessions, and how PHP manages state across different web requests. In a stateless protocol like HTTP, sessions provide a way to store information about a user across multiple requests. Mastery of session management is key to developing interactive and personalized web applications with PHP.

Resources for Interview Preparation

  • HackerRank Interview
  • Tech Interview Prep: How To Ace Your Interview

This article was written with the help of AI. Can you tell which parts?

Get started with HackerRank

Over 2,500 companies and 40% of developers worldwide use HackerRank to hire tech talent and sharpen their skills.

Recommended topics

  • Coding Questions
  • Interview Preparation

Abstract, futuristic image generated by AI

6 REST API Interview Questions Every Developer Should Know

DEV Community

DEV Community

Eric The Coder

Posted on Apr 6, 2021 • Updated on Apr 7, 2021

Learn by Doing: Practice PHP OOP (level 1)

If you like this post and want more connect with me on Twitter: Follow @justericchapman

You want to learn PHP OOP for a long time but you keep postponing? Now is the time! For the next 30 days I will post php OOP exercises + solution.

Your challenge is to try to solve the small exercise without looking at the solution. You can use the web to search for concept but please dont look at the solution before at least try to solve the exercise.

We will start very easy but don't be bored because exercises will quickly became more and more challenging....

Challenge accepted?

Exercise #1

In OOP class is like the blueprint and object are the instance. For example a house plan would be the class but the houses that will be construct base on that plan will be the objects.

Your first challenge is to create a class name Product and create a instance of that class name product1

Exercise #2

Since exercise #1 its pretty easy why not go for another one right now.

So we have a class named Product. A Product can have properties like name, description, price, etc. We can define variables like $name, $description, and $price to hold the values of these properties.

When the individual objects (product1, product2, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

For the second exercise add properties (name, description and price) to the class Product. A little hint. We create properties like we create a variable but the property need to have an access modifier prefix: public, private or protected. We will cover more on that later. For now use the public prefix.

After that go to the instantiated object product1 and modify the property name for 'iPhone 12'. Then you can: echo product1->name to see the result.

Last but not least, create a second object name product2 and set is name property to 'iPhone 12 Pro' and echo out that property.

Ready? Let's do it now!

STOP... Do the exercises first! It's the only way you will really learn.

If you have done your exercise here my solution. Noted most of the times, more than one solution will be possible. If you have something different that me, leave your solution in the comment to share and discuss.

Exercise 1 solution:

Exercise 2 solution:.

That's it for today. Tomorrow the journey continue, see you later!

If you want to be contribute you can re-tweet this post on tweeter Follow @justericchapman

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

abdurrahman720 profile image

Add swipe-able button in React

Abdur Rahman - Feb 29

kecbm profile image

Apple and Orange

Klecianny Melo - Mar 28

best_codes profile image

What is a Service Worker? ✨🦸

Best Codes - Mar 26

henrylehd profile image

Understanding JavaScript and TypeScript: A Beginner's Guide

Henry Dioniz - Mar 26

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

5 problems a PHP developer can solve for your application or website

problem solving with php

PHP is commonly claimed as the best programming language in the world for commercial projects. It can be used to build websites and applications in an efficient, secure, and scalable manner, but PHP alone won’t carry the success of a project.

To make the most of the language to build the best possible platforms, businesses need to hire top-tier developers who can use PHP to its full potential .

Hiring a PHP developer? Read on for a breakdown of the skills you should be looking for in your candidates and an exploration of five problems a PHP developer can solve for your application or website.

Table of contents

What is php, php developers: who are they and what do they do, 5 essential skills for php developers, testing php coding skills.

PHP is a server-side scripting language, embedded in HTML, that is used by programmers and developers to develop dynamic websites and applications. It’s been around for a long time: It was originally created in 1994 and has since been adjusted over and over again.

PHP is open-source and general-purpose , so it’s a popular and highly practical language. As of May 2022, W3Techs reports that it is used by 77.4% of websites whose server-side language is known.

Confusingly, PHP stands for PHP: Hypertext Processor . Yes, the P in PHP stands for PHP. We call an acronym that refers to itself like this a recursive acronym – originally, PHP stood for Personal Home Page .

Common uses of PHP in web development include, but are not limited to:

Performing system functions like creating, opening, reading from, writing to, and closing files

Adding, deleting, and modifying elements within a database

Accessing cookie variables and setting cookies

Restricting user access to certain web pages

Encrypting user data to enhance privacy

Connecting web pages with databases

Counting the visitors on a site at any given time

PHP is still a top choice for web development because it’s easy to use . It’s also open-source , and therefore free. It’s fast and secure, and is highly versatile, with a strong and loyal community behind it.

global websites that use PHP

Because it’s been around for so long, it’s been tried and tested in real-life scenarios far more than other programming languages. Facebook and WordPress are probably the most famous examples of software written on PHP. It’s a reliable veteran, trusted by developers everywhere.

PHP developers , also known as PHP engineers , are a subcategory of developers who use PHP to write server-side web application logic. They are responsible for testing , troubleshooting , and maintaining the code. Their duties usually include:

Writing back-end PHP code to create or modify software and applications

Developing, testing, and launching website applications with precision and efficiency

Analyzing website and application requirements

Identifying and then solving issues that involve scripting in CSS and HTML

Setting and meeting performance objectives for client systems

Most of the time, PHP developers will work as part of a team of developers or engineers. But smaller businesses and organizations tend to seek very well-rounded developers since they don’t have the resources to recruit a whole team with people for each specialist task.

Although different PHP developers will be experts in different areas, it’s a good idea to keep your general PHP proficiency up to scratch if you want to be a competitive candidate for companies.

5 essential skills for PHP developers

Knowledge of and proficiency in PHP functions

This is an obvious one. To be a good PHP developer, you need to have mastered basic PHP skills. This means you’ll have a strong grasp of the language, its operations, its functions, and its applications.

PHP developers should also be familiar with some of PHP’s frameworks; Laravel is the most popular, Symfony , CodeIgniter , and Zend are some other examples. You can read our blog post about PHP Laravel developers to find out more about what they do specifically.

They may also need to have some knowledge of other programming languages . Knowing PHP alone sometimes won’t be enough. An understanding of some front-end languages, like JavaScript , CSS , and HTML , will help them spot and correct web design errors.

Ability to follow PHP best practices

PHP has been around for a long time and has undergone many adjustments and updates . Its popularity means it evolves quickly, and countless frameworks have been born and died as people try to get the best out of it.

This means there’s lots of outdated information around, and it can lead to bad PHP practices and ineffective code. There are living PHP information documents scattered about online to try and combat this, but some general best practices for PHP developers include:

Make your code concise and readable, and document it properly . This is a golden rule for anyone writing code. That being said, don’t over-comment your code: Documentation is important, but save it for the most complicated parts of your source code.

Make the most of core functions and classes . Chances are there’s already one that covers what you’re trying to do, so developers should check the PHP manual before creating their own functions.

Use the PHP Standard Recommendation (PSR). Published by the PHP Framework Interoperability Group (PHP-FIG), PSR is a specification that aims to standardize programming concepts in PHP. It’s especially useful when coders are collaborating across multiple projects.

Use a good source editor . A good text editor saves developers time by helping them avoid syntax errors. Most will have handy features to optimize workflow, like code hinting or code navigation.

Keep code snippets . This could save you lots of time – PHP developers will end up coding a lot of the same things throughout their careers. There are plenty of apps designed to help developers collect and keep code snippets.

Create a master file, or configuration file, for your database connection settings . This will make your code easier to maintain, especially when you’re working with certain constants and functions through multiple scripts.

Turn on error reporting in the development stages of application-building . Developers should do this to identify run-through errors as soon as possible – the sooner you know an error is there, the faster you can fix it.

It’s essential that PHP developers follow best practices, and keep a finger on the pulse of how the language is changing.

Object-oriented programming

Object-oriented programming (OOP) is a type of programming that relies upon objects and classes to organize software design, rather than using functions and logic like procedural programming does. An object is defined as a data field that has unique attributes and behaviors, and a class is just an organizational unit (so objects are organized by development classes).

Basically, procedural programming involves writing procedures or functions which then perform operations on your data, and object-oriented programing is about creating objects that contain functions and data .

The latest versions of PHP are object-oriented , meaning functionality is built into objects and developers can write their classes to organize them. However, PHP is not purely an object-oriented language: These versions still have huge collections of functions, they just adhere to an OOP paradigm. This had led to disagreements among developers about exactly how object-oriented PHP is.

Regardless of their opinions on how object-oriented PHP is or isn’t, PHP developers need object-oriented programmer skills to use the latest versions of the language.

Problem-solving skills

The reason any code in any language gets written in the first place is that there’s a problem, and it needs solving. And anyone in the software development and engineering field will tell you that it’s truly a problem-solving, mentally intensive field.

Problem-solving is the core thing software developers do. The programming languages and tools they use are secondary to this fundamental skill. The Odin Project

Hiring developers who can bring problem-solving skills to the workplace will be crucial to the success of your website or application.

kathryn barrett quote

Communication skills

Communication skills are considered essential to any productive working environment. But 86% of employees and executives cite a lack of effective communication and collaboration as the leading cause of errors in their workplace.

Software engineering and development is no exception to the universal importance of communication. In fact, good communication is especially important in development teams because there will likely be a knowledge gap between what they know about how your website or application works and what the rest of your teams know.

Although there is plenty you can do to improve communication in the workplace once you’ve hired a PHP developer, hiring someone with excellent communication skills in the first place might be sensible. Read our guide to communication assessment tools for more.

5 problems a PHP developer can solve for your website

1. Website customization

A skilled PHP developer will be well equipped to help you customize your website or application. So, if things need jazzing up, you should recruit a developer with the skills listed above.

Server-side PHP is the best tool for building custom websites because it has very few limitations . Programmers can use it to create a platform that matched their clients’ needs exactly.

For evidence of how versatile it is, think about the fact that websites and platforms as diverse as Slack , Etsy , MailChimp , and Wikipedia use PHP to power their back-ends. Despite their differences, these are vast and sophisticated platforms that are also easy to handle from the programming side.

This is the beauty of PHP. It’s also great for scalability , so if you’re focussed on growing and increasing traffic, as most businesses are, you should consider PHP for your server-side programming.

2. Enhanced security

The level of security that PHP can provide is often debated. Its vulnerabilities are well documented, and identical PHP applications are widely deployed, meaning a liability in one application can result in a large number of insecure servers.

This being said, PHP is just as secure as any other major server-side language. And, as with other languages, the key to programming a secure website lies in how you use it. All programming languages are vulnerable – the security comes when developers use them effectively.

PHP has undergone some important, security-related updates over the past few years, but knowledgable , skilled , and experienced PHP developers are your best bet when it comes to making sure everything is configured securely. Hackers feed on poor development practices. Hire a PHP developer to write safe, secure code for your website or application.

3. Connecting to databases

PHP is an especially good language for interacting with databases. It can support a large variety of databases and makes it easy to handle and redirect data. The database options it can support include, but are not limited to:

Firebird/InterBase

With a great PHP developer on your team, you can be choosy about which databases you want to use. The best PHP developers will ensure your website or application is performance-optimized.

4. Sanitizing inputs and outputs

Data must be sanitized before it is sent to a database. Sanitization is one of the most common and also one of the most important tasks in web application development; it involves the checking, cleaning, and filtering of inputs from users, APIs, and web services of any unwanted bits. This way, harmful codes are prevented from entering the system.

Similarly, any data that an application or website retrieves from other sources needs to be sanitized before it’s shown to users. This is known as output sanitization . Hackers tend to target the gap in the interactions between website and server, encoding special characters to carry out unauthorized actions, so sanitization is really important.

PHP makes sanitization tasks easier: It provides a native filter extension that developers can use to sanitize user data, ensuring it meets security requirements. It also has various useful functions for sanitization, such as the addslashes () function and the strip_tags () function.

5. Fixing any existing errors

There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should. If you have an existing PHP-based website or application that is experiencing performance issues , hiring a great PHP developer is your best chance at fixing things up quickly and effectively.

Top PHP developers will be able to properly track and fix bugs , and update your code to make sure your program runs smoothly again. Here are a few strategies developers might use to fix existing PHP errors:

Utilize their knowledge of defensive programming practices

Separate code from its environment configuration files

Use assertion condition tests to track PHP errors

Send PHP errors to an error log file, add context, and monitor the log

Now that we know about PHP development skills and some of the problems these skills can help developers solve for websites and platforms, let’s get thinking about how you can ensure you hire a great PHP developer for your company .

PHP is a great language, but, as we’ve discussed, the benefits can only be reaped if developers are using it effectively. Experience is useful, but this requires skill more than anything, so it makes sense to u se a skills-based approach if you’re recruiting a developer.

Pre-employment skills assessments are the best way to practice skills-based hiring. They set candidates on an even playing field to measure how their skills compare in practice, rather than on paper.

The right combination of skills tests can open up a depth of understanding of your candidates (their skills and their personalities) that CVs and resumes can’t provide for recruiters. Because of this, you should test PHP development candidates right at the start of your hiring funnel .

TestGorilla’s PHP (coding): Object-Oriented Programming test assesses PHP development skills

This might sound intimidating – but TestGorilla has you covered. Our PHP (coding): Object-Oriented Programming test is designed specifically to evaluate object-oriented programming skills and help you identify, and hire, the best mid-level PHP developer for you.

PHP (coding) test

How does it work?

The PHP test is geared toward mid-level PHP developers, so it’s a great test to use for the initial screening of your candidates if you want to assess their object-oriented programming skills.

When candidates enter the test, they’ll see something similar to this:

test preview

A real-life scenario is presented, and candidates have 30 minutes to implement a piece of code that meets the requirements outlined in the text. Your candidates will all be presented with the same scenario, which is drawn from a pool of questions generated, peer-reviewed, and tested by subject-matter experts.

what does the PHP test involve

Once your candidates have reviewed and submitted their code, you’ll be able to see their score, which is generated automatically from a set of test cases, and play the coding editor back to see how they reached their answer.

If you’re interested in assessing candidates for a different level of PHP proficiency, we also offer the following PHP-related tests:

PHP (coding): Intermediate-Level Algorithms

PHP (coding): Entry-Level Algorithms

how is the PHP test scored

Use PHP tests as part of a complete skills assessment

Although we could sing away about how great this test is, it’s important to remember that it shouldn’t be used alone to evaluate candidates. You can sift through our ever-expanding test library to find other relevant tests for your candidates: We recommend using two to five, along with any important custom questions, to build a complete assessment.

For any of our coding tests, we recommend using them in combination with a cognitive ability test . Our cognitive ability tests include:

Attention to detail (visual)

Attention to detail (textual)

Mechanical reasoning

Reading comprehension

Critical thinking

Numerical reasoning

Problem-solving

Spatial reasoning

Listed below are some other tests you could use to help you identify the right PHP development candidate for you.

This test evaluates candidates’ coding skills using a short coding assignment that they’ll have 30 minutes to complete. They will have to write a code to meet certain requirements and can run and test the code throughout the assessment.

SQLite (coding): Intermediate-Level Querying

Assesses candidates’ skills in creating a mid-complexity query on a database by immersing them in a real-life problem that needs solving with intermediate SQLite querying skills. We also have an SQLite (coding): Entry-Level Database Operations test, and an SQLite (coding): Complex Queries test.

The CSS developer test can be used to identify candidates who are knowledgeable about and skilled in CSS concepts and techniques. You can use this test if you want to hire a developer who can use CSS to create websites and applications. You can add CSS styling to pages generated using PHP.

Clean code is important for any kind of software engineer. Use this test to ensure you hire a PHP developer who can write code that is easy to maintain.

Laravel is the framework most popularly used with PHP. Candidates who do well on this test will be able to create, update, and maintain applications using Laravel – so, if your application uses Laravel, this test is a must.

Hiring a developer has never been easier

There’s often a knowledge gap between recruitment teams and software development candidates that can make the hiring process a struggle. Skills assessments bridge this gap to make employment processes stress-free. They also bring the bonus of reducing the hiring biases that traditional recruitment practices are riddled with.

If by now you’re convinced that TestGorilla can help you hire the right developer, PHP or otherwise, for your company, you can sign up for free today. Alternatively, take a look at our pricing plan and choose an option that best suits your organization. And if you’re not convinced, you can always book a free live demo with our sales team.

Related posts

The tech skills gap: What it is, why it exists, and how to close it in 2024 featured image

The tech skills gap: What it is, why it exists, and how to close it in 2024

7 hiring trends for 2024 and beyond featured image

7 hiring trends for 2024

 Most accurate 16 personalities tests for assessing candidates featured image

Most accurate 16 personalities tests for assessing candidates

Hire the best candidates with TestGorilla

Create pre-employment assessments in minutes to screen candidates, save time, and hire the best talent.

problem solving with php

Latest posts

12 essential front end developer skills and how to assess them featured image

The best advice in pre-employment testing, in your inbox.

No spam. Unsubscribe at any time.

Hire the best. No bias. No stress.

Our screening tests identify the best candidates and make your hiring decisions faster, easier, and bias-free.

Free resources

problem solving with php

This checklist covers key features you should look for when choosing a skills testing platform

problem solving with php

This resource will help you develop an onboarding checklist for new hires.

problem solving with php

How to assess your candidates' attention to detail.

problem solving with php

Learn how to get human resources certified through HRCI or SHRM.

problem solving with php

Learn how you can improve the level of talent at your company.

problem solving with php

Learn how CapitalT reduced hiring bias with online skills assessments.

problem solving with php

Learn how to make the resume process more efficient and more effective.

Recruiting metrics

Improve your hiring strategy with these 7 critical recruitment metrics.

problem solving with php

Learn how Sukhi decreased time spent reviewing resumes by 83%!

problem solving with php

Hire more efficiently with these hacks that 99% of recruiters aren't using.

problem solving with php

Make a business case for diversity and inclusion initiatives with this data.

21 Essential PHP Interview Questions  *

Toptal sourced essential questions that the best php developers and engineers can answer. driven from our community, we encourage experts to submit questions and offer feedback..

problem solving with php

Interview Questions

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:

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

What will this code output and why?

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:

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 be the output of the code below and why?

The output will be as follows:

Here’s are the two key facts that explain why:

  • The term $x++ says to use the current value of $x and then increment it. Similarly, the term $x-- says to use the current value of $x and then decrement it.
  • The increment operator ( ++ ) has higher precedence then the sum operator ( + ) in order of operations.

With these points in mind, we can understand that $x+++$x++ is evaluated as follows: The first reference to $x is when its value is still 5 (i.e., before it is incremented) and the second reference to $x is then when its value is 6 (i.e., before it is again incremented), so the operation is 5 + 6 which yields 11. After this operation, the value of $x is 7 since it has been incremented twice.

Similarly, we can understand that $x---$x-- is evaluated as follows: The first reference to $x is when its value is still 7 (i.e., before it is decremented) and the second reference to $x is then when its value is 6 (i.e., before it is again decremented), so the operation is 7 - 6 which yields 1. After this operation, the value of $x is back to its original value of 5, since it has been incremented twice and then decremented twice.

Apply to Join Toptal's Development Network

and enjoy reliable, steady, remote Freelance PHP Developer Jobs

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

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) 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?

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

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:

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

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

The correct answer is 18.

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).

Please note that as of PHP 7.2, this code produces an error.

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

After the above code is executed, the value of $text will be the string “ John D ” (i.e., “John”, followed by six 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 five. 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 five-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.

What does the follow code echo?

The number 1 .

Note, in PHP 7.2 this throws a warning that a non-numeric value is encountered on the line and does not do the conversion to the int , so it echoes PHP instead.

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:

After sorting, should become:

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

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 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.

What is PEAR in php?

PEAR ( P HP E xtension and A pplication R epository) 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 is use of the header() function in PHP?

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

Consider the following code:

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).

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.

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

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.

What is the difference between a session and cookies?

A session stores the value on the server and cookies store the value in the user’s browser.

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

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

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

The output will be:

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

The problem here is that strpos() returns the starting position index of $str2 in $str1 (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:

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 .

There is more to interviewing than tricky technical questions, so these are intended merely as a guide. Not every “A” candidate worth hiring will be able to answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains an art, a science — and a lot of work .

Tired of interviewing candidates? Not sure what to ask to get you a top hire?

Let Toptal find the best people for you.

Our Exclusive Network of PHP Developers

Looking to land a job as a PHP Developer?

Let Toptal find the right job for you.

Job Opportunities From Our Network

Submit an interview question

Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.

Looking for PHP Developers?

Looking for PHP Developers ? Check out Toptal’s PHP developers.

Jay Johnston, Freelance PHP Developer for Hire.

Jay Johnston

Coding HTML, CSS, and JavaScript since his armed forces days in 1997, Jay enjoys bringing value to clients via eCommerce solutions, legacy integrations, and optimized PHP and JavaScript-driven applications. His preferred DevOps environment is AWS, where he has strong skills in (and not limited to): Relational Database Services (RDS), Redshift, Dynamo DB, Data Migration Services (DMS), Lambda (serverless and microservices), Cloudwatch, Cloudtrail, and Event Bridge.

Igor Santos, Accomplished PHP Freelancer.

Igor Santos

Igor is a web developer focused on modern PHP and JS, always striving for new technologies. When he wears his back-end hat, he's focused on performant and DRY code, working on API servers or consumers. When he gets his front-end hat on, he works heavily on maintaining the best UX he can make for his users.

David Marín, Freelance PHP Programmer for Hire.

David Marín

David is an open-source and open-data enthusiast with more than 23 years of experience as a professional developer. He has acquired various skills, including web programming (PHP and JavaScript), C, C++ (under Linux and Windows), and systems management. Of these skills, David specializes in web programming and has full-stack experience with Symfony PHP-based back ends, jQuery front ends, and WordPress/WooCommerce-based sites.

Toptal Connects the Top 3% of Freelance Talent All Over The World.

Join the Toptal community.

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

problem-solving

Here are 32 public repositories matching this topic..., mesripour / hacker-rank.

HackerRank solutions in PHP

  • Updated Oct 10, 2020

vatttanweb / CodilityChallenges

Challenges that had been introduced by Codility was solved in this repository.

  • Updated Jan 23, 2023

rosairekota / convertor

This library help you to convert numbers to letters.

  • Updated May 18, 2023

RamyHakam / egypt-microbus

How to optimize the load and unload of the MicroBus in Egypt

  • Updated Dec 20, 2021

Shipu / php-algorithms-implementation

Algorithms Implementation using PHP

  • Updated Mar 13, 2017

ArjunAranetaCodes / MoreCodes-PHP

Computer Programming Problems and Solutions with the PHP Language

  • Updated Nov 11, 2018

Amir-16 / leetcode-problem-solutions

Leetcode problem Solutions

  • Updated Apr 3, 2024

BakhadyrovF / leetcode

LeetCode problems with solutions

  • Updated Mar 1, 2023

girish004 / Local-Social-Media

A social media website, which is mostly restricted to one particular community like schools, colleges, etc made using PHP, HTML, CSS

  • Updated Feb 9, 2021

MockingMagician / moneysaurus

Money change library. A Solution for change-making problem.

  • Updated Jul 21, 2019

Hades1295 / Leetcode

Solving Leet codes every Day

  • Updated Nov 15, 2022

morrismukiri / josephus

An implementation of the Josephus problem

  • Updated Feb 7, 2017

mrbvrz / cheat-sheet

☕ Cheat Sheet - just a set of problems and solutions that I usually encounter

  • Updated Aug 10, 2023

ashraf789 / Hackerrank-problem-solving

All my solutions to get 5 * (gold) badge in both SQL and Problem solving.

  • Updated Dec 14, 2021

AhmedYahyaE / problem-solving

This is my Problem Solving repository for some of the top online coding challenges platforms

  • Updated Dec 25, 2023

mehedimi / series

This is a simple console application using sympony console component

  • Updated Jul 22, 2019

codingbysaikat / hackerrankProblemSolvingWithPHP

  • Updated Aug 26, 2022

Olayiwole / Fun-and-Hacks

I enjoy a good challenge and solving problems is an hubby, thus the reason why the fun and hacks repo was created.

  • Updated Mar 22, 2019

rajibkuet07 / data-structures

Data structures and algorithms in PHP and JS. Random problem solving with the explanation.

  • Updated Nov 18, 2022

nihat-js / solve-math-expression-php

(5+5/2)+(5*4*2/2+7) without eval function

  • Updated Jan 19, 2023

Improve this page

Add a description, image, and links to the problem-solving topic page so that developers can more easily learn about it.

Curate this topic

Add this topic to your repo

To associate your repository with the problem-solving topic, visit your repo's landing page and select "manage topics."

30 PHP Coding Interview Questions for Developers

php coding interview questions

Modern web development would be incomplete without PHP, a robust and flexible scripting language. It is part of the famous LAMP stack, which includes PHP as the core programming language. 

This article provides extensive PHP programming challenges appropriate for developers of all skill levels. This article will present a wide variety of coding tasks, from predicting the results of code snippets to finding bugs in the code. Technical hiring managers can use these challenges to assess candidates for knowledge of PHP and its frameworks, and ultimately find the best applicants for a given role.

Interview Questions for Beginner PHP Developers

When preparing coding challenges for beginner PHP developers, it’s important to evaluate fundamental concepts and skills related to PHP and Laravel. Some areas which must be assessed include basic PHP syntax, control structures, functions, arrays, strings and sessions. Here are 10 coding challenges in this regard:

Predict the output of the below code:

Guess the output of the below code:

Identify the issue in the below code:

You need to write a PHP script that will convert temperatures between Celsius and Fahrenheit. The input parameters should be the temperature value and the unit (Celsius or Fahrenheit). The script will return the converted value in the other unit.

Will the below code throw any error? If yes, identify the error.

Create a PHP script that shows a list of products in a simple e-commerce catalog. Each product will have a name, description, price and featured image. You can store the product data in an array, a JSON file or a database. The script should generate an HTML page that will display the product details in a user-friendly format.

Analyze the below code and suggest the output:

Find the issue with below code snippet:

Question 10

Analyze the below code and identify the issue.

Interview Questions for Mid-level PHP Developers

When designing interview questions for mid-level PHP developers, you should prepare challenges aiming to assess advanced concepts of PHP and web development. Some areas that should be evaluated include advanced object-oriented programming (OOP), design patterns, database interaction, restful APIs and exception handling. Below you will find 10 coding challenges which are ideal for mid-level PHP developers:

What is the issue in the below code:

Implement a set of RESTful APIs to create a simple e-commerce website. The website will have features like the ability to browse products, add items to a shopping cart and checkout using the Stripe payment gateway. Use OOP principles and design patterns like factory method pattern, dependency injection and observer pattern to write scalable, modular and testable code. You need to handle exceptions gracefully by logging and displaying errors to users in a user-friendly manner.

Build a social network platform using PHP and MySQL. The platform should allow users to create profiles, add friends, post status and comment on their friends’ statuses. Use design patterns like decorator pattern, factory pattern and observer pattern to ensure modularity, scalability and testability. Implement RESTful APIs for user authentication, content creation and display. Make sure you handle exceptions for error reporting and logging.

Will the below code throw any error?

What will be the output of the below code:

Analyze the below code and suggest if it is vulnerable to an injection attack.

You need to develop a file management tool using PHP that allows users to upload, download and manage files. Use adapter and factory design patterns to handle file storage and retrieval. Use exception handling to handle errors and provide feedback to users.

Analyze the below code and advise what the issue is in the below API call:

You need to build an online booking system using PHP. Some of its features would be to allow users to book appointments or make reservations. Use design patterns like the observer pattern and the decorator pattern to manage notifications and user interface elements.

Interview Questions for Expert PHP Developers

When preparing coding challenges for expert-level PHP engineers, you should pay attention to strong problem-solving skills, the design and architecture of the system and expertise in the framework. Some of the core areas for evaluating expert PHP programmers are advanced database interaction, performance optimization, security, CI/CD, cloud infrastructure and advanced debugging. Find 10 coding challenges for expert PHP engineers below:

Do you see any security issue in the below code? If yes, how would you correct it?

Can you predict the output of the below query?

Can you guess the duration of the script execution?

Can you optimize the code snippet provided in the previous challenge so that it takes less time to execute.

Develop a RESTful API for a SaaS application that handles user authentication, role-based access control, rate limiting, versioning and proper error codes. Ensure the API follows best practices and developers can easily consume it.

Analyze the below code and optimize it in terms of memory management.

Can you guess what is wrong with below execution of the API call?

You need to develop a report generation system for an e-commerce platform that can handle complex queries and join multiple tables. Users should be able to generate reports in various formats (e.g. CSV, JSON, PDF). Implement the solution using advanced database interaction techniques and optimize for performance.

What is wrong with the below code?

Implement a search feature that supports pagination, filtering and sorting for an e-commerce website. Use PHP Data Objects (PDO) or a popular ORM like Eloquent (from Laravel) to interact with the database. Use prepared statements and query builders. Extra marks if you use the Laravel framework.

Developer Skill Assessment Tool

This article has presented a diverse set of PHP code challenges that help technical recruiters and hiring managers to evaluate PHP professionals at different career levels. These challenges assess candidates’ PHP proficiency and problem-solving skills. The categorization of these challenges into beginner, mid-level and expert categories makes it easier for technical managers to evaluate a PHP candidate accordingly.

Further reading:

  • Java Coding Interview Questions
  • Python Coding Interview Questions
  • ReactJS Coding Interview Questions
  • JavaScript Coding Interview Questions
  • C# Coding Interview Questions
  • C++ Coding Interview Questions
  • 73 Advanced Coding Interview Questions
  • Share on Facebook
  • Email this Page
  • Share on LinkedIn

DevsENV

PHP Bonus - Online Judge Problem Solving Using PHP

  • Problem Solving
  • Popular online problem solving platforms -
  • How we’ll solve the problems ?
  • Test in Online PHP Code -
  • Problem Details
  • Solution in PHP
  • Problem 2: Extremely Basic
  • Problem 3 - Multiples
  • Problem 4 - Upto Odd Numbers

¶ Problem Solving

Todays, lecture is totally different from PHP programming language aspects. This is for both PHP and all general level programming languages. Problem Solving is a very important parts to becoming a very good Developer. In our practical life, we’ll face lots of different and new problems every day when we starts our real project. If we have proper problem solving skills, then we can easily solve any problem easily. Let’s try solving some of the problems in popular online judge programming platform.

¶ Popular online problem solving platforms -

  • BeeCrowd - https://www.beecrowd.com.br/judge/en
  • UVA Online Judge - https://onlinejudge.org
  • HackerRank Online Judge - https://www.hackerrank.com
  • CodeForce Online Judge - https://codeforces.com
  • LightOJ - https://lightoj.com

And there is so many online programming problem solving websites out there. We’ll start using the easiest one BeeCrowd or previously URI online judge.

¶ BeeCrowd Online Judge

BeeCrowd is one of the most popular online judge problem solving platform. It’s suitable for both beginner, intermediate and advanced level users.

¶ How we’ll solve the problems ?

We’ll read the problems very carefully and solve those problems using PHP language. You can try with other language also if you’re comfortable. We’ll solve some Beginner Level problems - https://www.beecrowd.com.br/judge/en/problems/index/1

¶ Test in Online PHP Code -

https://onecompiler.com/php/3y5ak79p9

¶ Problem 1: Hello World

https://www.beecrowd.com.br/judge/en/problems/view/1000

¶ Problem Details

Hello world.

problem solving with php

Welcome to beecrowd !

Your first program in any programming language is usually " Hello World! ". In this first problem all you have to do is print this message on the screen.

This problem has no input.

You must print the message Hello World! and then the endline as shown below.

¶ Solution in PHP

¶ problem 2: extremely basic.

https://www.beecrowd.com.br/judge/en/problems/view/1001

¶ Problem 3 - Multiples

https://www.beecrowd.com.br/judge/en/problems/view/1044

¶ Problem 4 - Upto Odd Numbers

https://www.beecrowd.com.br/judge/en/problems/view/1067

All Tutorials in this playlist

What is PHP, it's History, How it Works under the hood in web

What is PHP, it's History, How it Works under the hood in web

Install PHP or Xampp in Windows / Linux / Mac - Easy PHP Server setup

Install PHP or Xampp in Windows / Linux / Mac - Easy PHP Server setup

Run our First PHP Program

Run our First PHP Program

Variables in PHP - How to Create, Rules and Examples

Variables in PHP - How to Create, Rules and Examples

Data Types in PHP - Variable Types in PHP

Data Types in PHP - Variable Types in PHP

Echo, PHP Statement, Print, Concat and Comments in PHP

Echo, PHP Statement, Print, Concat and Comments in PHP

PHP Operators - Arithmetic operator, Assignment Operator, Increment-decrement Operator

PHP Operators - Arithmetic operator, Assignment Operator, Increment-decrement Operator

PHP Operators Part 2 - Comparison Operator, Logical Operator, Conditional Operator

PHP Operators Part 2 - Comparison Operator, Logical Operator, Conditional Operator

PHP If-else-elseif and Switch-case

PHP If-else-elseif and Switch-case

PHP Math Functions - pi, abs, sqrt, min, max, rand, round, floor, ceil, pow, is_nan, is_numeric

PHP Math Functions - pi, abs, sqrt, min, max, rand, round, floor, ceil, pow, is_nan, is_numeric

PHP String Functions - All necessary String functions in PHP to manage strings better.

PHP String Functions - All necessary String functions in PHP to manage strings better.

Loops in PHP - for, while, foreach, do-while

Loops in PHP - for, while, foreach, do-while

PHP Array and all it's Examples

PHP Array and all it's Examples

PHP Array Part 2 - Array Built in PHP Functions and Some More Examples

PHP Array Part 2 - Array Built in PHP Functions and Some More Examples

PHP  - Functions in PHP - How to create and how to use

PHP - Functions in PHP - How to create and how to use

PHP Loosely Type Language - Strict type from PHP 7

PHP Loosely Type Language - Strict type from PHP 7

PHP Superglobal Variables and It's Practical Examples - Get, Post, Session, Cookie, Request, Server

PHP Superglobal Variables and It's Practical Examples - Get, Post, Session, Cookie, Request, Server

Form Submission and File Upload in PHP - Basic to Advance Level Form Submission in PHP

Form Submission and File Upload in PHP - Basic to Advance Level Form Submission in PHP

PHP OOP - Object Oriented Programming Introduction

PHP OOP - Object Oriented Programming Introduction

Popular tutorials, vue js 3 - complete advance crud example with vuex, vue-validate, pagination, searching and everything, laravel eloquent vs db query builder [performance and other statistics], laravel role permission management system full example with source code, start wordpress plugin development with react js easily in just few steps, laravel membership management full project demo with source codes, numerical methods for engineers ebook & solution download - download pdf, connect your react app with websocket to get real time data, #ajax with laravel api and more - learn laravel beyond the limit, laravel ecommerce complete web application with admin panel, what is seeder in laravel and why we need it.

  • Artificial Intelligence (AI)
  • Bash Scripting

Bootstrap CSS

  • C Programming
  • Code Editor
  • Computer Engineering
  • Data Structure and Algorithm

Design Pattern in PHP

Design Patterns - Clean Code

  • Git Commands

Interview Prepration

Java Programming

Laravel PHP Framework

Online Business

  • Programming

React Native

Rust Programming

Tailwind CSS

Uncategorized

Windows Operating system

  • Woocommerce

WordPress Development

  • C-sharp programming
  • Design pattern
  • Mathematics
  • Rust Programming Language
  • Windows terminal
  • WordPress Plugin Development

MarketSplash

How To Dump PHP Variables For Debugging In TextMate

Debugging PHP in TextMate can be streamlined with the right techniques for dumping variables. This article guides you through practical methods and tools to enhance your debugging skills, ensuring efficient problem-solving in your PHP projects.

💡 KEY INSIGHTS

  • Utilizing custom snippets in TextMate for frequently used debugging functions like `var_dump()` can significantly expedite the debugging process.
  • Integrating external tools such as Xdebug with TextMate enhances PHP variable debugging, offering advanced features like breakpoint debugging.
  • For more readable output, wrapping variable dumps in 'pre' tags is essential, especially when dealing with complex data structures .
  • Creating a conditional debugging setup within TextMate allows for focused and efficient troubleshooting, especially in large-scale PHP applications.

Debugging in PHP can be tricky, but with the right tools and techniques, it becomes much easier. This guide focuses on using TextMate to efficiently dump and analyze PHP variables. We'll walk you through simple yet effective methods to enhance your debugging process, making error tracing and resolution more straightforward.

problem solving with php

Understanding PHP Variable Debugging In TextMate

Setting up textmate for php debugging, basic techniques to dump php variables, advanced variable dumping strategies, troubleshooting common issues, optimizing the debugging workflow, frequently asked questions.

Debugging is a crucial part of any programming process, especially in PHP, where variables can often have complex structures or unexpected values. In TextMate, a popular editor among developers, debugging can be done efficiently with a few simple tools and techniques.

Properly configuring TextMate for PHP debugging enhances your development experience, making it more efficient and less error-prone.

Installing And Configuring PHP In TextMate

Integrating php debugging tools, setting up custom bundles, utilizing textmate's built-in features, streamlining the debugging process.

Ensure that PHP is Correctly Installed and configured in TextMate. This includes setting the correct path to the PHP executable.

Integrate PHP debugging tools, such as Xdebug , into TextMate. This provides advanced features like breakpoint debugging and stack traces.

Customize or create TextMate Bundles for PHP to include debugging snippets and commands. This allows for quick insertion of debugging functions.

Leverage TextMate's Built-in Features such as bookmarks and folding to navigate and manage debugging code efficiently.

Streamline your debugging process in TextMate by Assigning Keyboard Shortcuts to commonly used debugging actions.

By setting up TextMate correctly for PHP debugging, you can significantly enhance your productivity and the effectiveness of your debugging sessions. These steps help in creating a tailored environment that supports a streamlined debugging process.

In PHP debugging, understanding the state of variables is crucial. Here, we'll discuss basic methods to dump variables, providing insights into their current state during script execution.

Using Var_Dump()

Using print_r(), formatting output for readability.

The var_dump() function is a straightforward way to output detailed information about a variable. It displays the variable's type, size, and value.

Another useful function is print_r() . It gives a more human-readable output compared to var_dump() , especially for arrays.

To enhance readability, especially in HTML contexts, wrapping your output in <pre> tags can be helpful.

Remember, the simplicity of these functions makes them powerful tools in the debugging process. Their ease of use ensures that you can focus on solving problems rather than struggling with complex debugging setups.

Moving beyond basic techniques, advanced strategies for dumping PHP variables provide more control and clarity. These methods are particularly useful for larger projects with complex data structures.

Custom Debugging Functions

Using xdebug, serialization for analysis, json encoding for readability, integrating with textmate.

Creating Custom Debugging Functions allows for tailored outputs. You can design a function that formats the variable information in a specific way that suits your debugging needs.

xdebug is a powerful PHP extension that enhances debugging capabilities. It offers improved variable output over the standard PHP functions.

Example with xdebug :

Sometimes, you might want to Serialize the variable data for analysis outside the debugging session. PHP's serialize() function turns a variable into a storable representation.

JSON Encoding is another method, useful for converting data to a readable and transportable format.

In TextMate, these advanced strategies can be incorporated through Custom Commands or Snippets , allowing for quick access and application during the debugging process.

Adopting these advanced methods enhances your ability to diagnose and resolve complex issues in your PHP code. They provide deeper insights and more manageable data formats, crucial for effective debugging.

When dumping PHP variables for debugging, developers often encounter a few common issues. Recognizing and resolving these can streamline your debugging process.

Invisible Output

Large array or object, memory limit errors, output interfering with html, variables not showing expected data.

Sometimes, the output of variable dumping is Invisible in the Browser . This is usually due to HTML rendering the output. Wrapping your debug output in <pre> tags can make it visible.

Dealing with a Large Array or Object can be overwhelming. Limiting the output to certain keys or levels helps in focusing on relevant data.

Memory Limit Errors occur when dumping very large variables. Increasing the memory limit temporarily can help.

When variable output Interferes with HTML layout, consider outputting the debug information in a comment.

If Variables Are Not Showing Expected Data , verify their scope and life cycle. Ensure they are being modified or set as expected.

Example Check :

Understanding these common issues and their solutions can significantly improve your debugging efficiency in PHP. Remember, the key is to adapt your approach based on the specific problem you're facing.

Efficient debugging in PHP requires a streamlined workflow. Optimizing this process can save time and reduce frustration.

Structured Debugging Approach

Utilizing conditional debugging, setting up efficient shortcuts, logging instead of outputting, cleaning up debug code.

Adopt a Structured Debugging Approach . Start by isolating the section of code where the issue might be, then use variable dumping strategically.

Conditional Debugging is useful for focusing on specific cases. Use conditions to dump variables only when certain criteria are met.

In TextMate, setting up Shortcuts for Debugging Commands can significantly speed up your workflow. Create snippets or keyboard shortcuts for commonly used debugging functions.

Consider Logging variable states to a file instead of outputting them directly. This is especially useful for debugging APIs or when working with AJAX.

Always remember to Clean Up Debug Code after resolving issues. This prevents the accidental output of sensitive data and keeps your codebase clean.

By implementing these strategies, you can create a more effective and less intrusive debugging workflow. This approach not only makes the process smoother but also ensures that your code remains clean and production-ready.

How can I handle debugging when working with large datasets or complex objects to prevent TextMate from becoming unresponsive?

When dealing with large datasets or complex objects, it's advisable to use selective dumping. Instead of dumping the entire dataset or object, target specific portions that are relevant to the issue you are debugging. This approach reduces the load on TextMate and prevents it from becoming unresponsive.

Can I set conditional breakpoints in TextMate for PHP like in an IDE?

TextMate, being a text editor, doesn't natively support conditional breakpoints like an Integrated Development Environment (IDE). However, you can mimic this functionality by inserting conditional statements in your code that trigger var_dump() or print_r() when certain conditions are met. This manual approach allows you to inspect variable states under specific scenarios.

Is it possible to integrate TextMate with external debugging tools for a more comprehensive debugging experience?

Yes, TextMate can be integrated with external debugging tools like Xdebug through its command line utility. This requires configuring the external tool with your PHP setup and creating custom commands in TextMate to interact with these tools. This setup allows for a more comprehensive debugging experience, albeit with some manual configuration.

How do I ensure that debug information doesn’t get exposed in a production environment when using TextMate for development?

To prevent debug information from being exposed in a production environment, it's crucial to have a clear workflow that separates development and production code. One approach is to use version control systems like Git to manage different branches for development and production. Ensure that all debugging code is removed or disabled before merging your development code into the production branch.

Let’s test your knowledge!

Which function provides a human-readable output of a variable in PHP?

Continue learning with these textmate guides.

  • How To Convert Text In TextMate
  • How To Create Multiple Insertion Points In TextMate
  • How To Edit Remote Files With TextMate
  • How To Edit Markdown In TextMate
  • How To Set Scoped Settings In TextMate: Effective Strategies

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

  • Share full article

People hold plastic water containers, waiting to fill them at a tap outside a store.

India’s Silicon Valley Faces a Water Crisis That Software Cannot Solve

Bengaluru gets plenty of rain. But the city did not properly adapt as its soaring population strained traditional water sources.

Filling up with subsidized water at a government distribution center in the Indian city of Bengaluru, also known as Bangalore. Credit...

Supported by

By Damien Cave

Photographs by Atul Loke

Reporting from Bengaluru, India

  • Published March 31, 2024 Updated April 2, 2024

The water tankers seeking to fill their bellies bounced past the dry lakes of India’s booming technology capital. Their bleary-eyed drivers waited in line to suck what they could from wells dug a mile deep into dusty lots between app offices and apartment towers named for bougainvillea — all built before sewage and water lines could reach them.

At one well, where neighbors lamented the loss of a mango grove, a handwritten logbook listed the water runs of a crisis: 3:15 and 4:10 one morning; 12:58, 2:27 and 3:29 the next.

“I get 50 calls a day,” said Prakash Chudegowda, a tanker driver in south Bengaluru, also known as Bangalore, as he connected a hose to the well. “I can only get to 15.”

People fill weathered plastic buckets with water that is coming out of a series of taps, lined up in a row.

The Silicon Valley of South Asia has a nature issue — a pain point that software cannot solve. In the sprawl beyond Bengaluru’s core, where dreams of tech riches usually grow, schools lack water to flush toilets. Washing machines have gone quiet. Showers are being postponed, and children with only dirty water to drink are being hospitalized with typhoid fever.

The big problem afflicting Bengaluru is not a lack of rain (it gets plenty, about as much as Seattle), but rather what often holds this giant, energetic nation back: arthritic governance. As the city rushed toward the digital future, tripling its population to 15 million since the 1990s and building a lively tech ecosystem, water management fell behind and never caught up as otherwise healthy aquifers were drawn dry by the unchecked spread of urban bore wells.

Failures of environmental stewardship are common across a country with severe pollution and an acute need for economic growth to provide for 1.4 billion people, spanning political parties and India’s north-south divide . But Bengaluru’s water struggle is especially withering for many — and motivating for some who have water sales or reform in mind — because the city sees itself as an innovator. And in this case, the causes and solutions are well known.

“There is no crisis of water availability,” said Vishwanath Srikantaiah, a water researcher and urban planner in Bengaluru. “It’s a clear-cut crisis of state failure.”

Viewed another way, he added in an interview at his home, where books about water and rivers were stacked nearly to the ceiling, it is a crisis caused by a lack of imagination.

As public policy experts tell it, Bengaluru and the broader state of Karnataka have been too slow to plan for growth, too divided across agencies and too rigid in their reliance on pumping water uphill from reservoirs along the Kaveri River more than 50 miles away.

Despite a long history of local hydrology — Nadaprabhu Kempegowda, the 16th-century founder of Bengaluru, built hundreds of cascading lakes for irrigation — officials have mostly stuck with the traditional engineering option that their predecessors turned to in the 1950s and ’60s.

That is the case despite its challenges and expense. The energy cost alone for pumping eats up 75 percent of the Bangalore Water Supply and Sewerage Board’s revenue, while supplying only around half of what the city needs.

The rest, for decades, has come from bore wells — holes about six inches wide that act like straws for water from aquifers below. An authority separate from the water board has punched 14,000 of them into the ground, half of which are now dry, according to officials. Experts estimate that residents have drilled an additional 450,000 to 500,000 into the cityscape, without the government’s knowing where or having a clear sense of their impact.

In much of the city, the wells are like doorbells, plentiful but seemingly invisible until someone points them out. Drilling failures appear as cutout circles on quieter streets; successes are often covered in flowers, with a black hose snaking into a home down the street.

Spending a day in the cab of Mr. Chudegowda’s tanker truck offered a glimpse of how the ad hoc system works. At one stop, drivers wrote their times in a logbook while cameras watched how much they took. At another the supply was slow and organized: A half-dozen drivers took 20-minute turns for fill-ups of around 6,000 liters, or about 1,600 gallons, just a few steps from a lake depleted to a puddle. At a third, a building owner sold a load to Mr. Chudegowda without the wait.

“Every minute counts,” he said as he climbed out of the truck.

His customers ranged from a bra factory with 100 workers to a small apartment building, all within a few miles to maximize profit. He charged each up to 1,500 rupees ($18) for each tanker load, more than double the going rate from a few months ago, which he considered justified because costs had gone up.

Drills — easily hired from companies with storefronts across the city — often fail to find water or have to go deeper now, which means more electricity and gas for the pumps pulling precious liquid from the earth.

The effects, while not at “Dune”-like levels, have become more visible in recent weeks, especially in the tech corridors, with their blur of luxury apartments, slums, mobile phone stores, malls, in vitro fertilization clinics and shimmering offices.

In Whitefield, a busy software hub, Sumedha Rao, a teacher at a new public school, offered to ask her class of 12-year-olds about their experiences with water scarcity. The hallways were painted in bright colors with words of encouragement — resilience, citizenship, collaboration. In class, they were asked how often they have water at home.

“One day a week, ma’am,” said a girl with pigtails.

“We just have a bucket,” said a boy near the back.

“There’s no water in the bore wells,” shouted another.

Many take small amounts of drinking water from school taps for their families — only one water bottle per child, because it is all the school can spare. Behind a play area the color and consistency of ground ginger sat a hulking pile of metal: a broken bore well.

“The motor stopped working,” said Shekar Venkataswamy, a physical education teacher with a brigand’s mustache.

Walking toward his home behind the school, he pointed to a dry hole where drilling failed, and one where it worked. A few thousand families take turns using the water for an hour each, with an elaborate schedule that is tightly managed.

Community leaders expressed pride in how they were handling the crisis, softening the blows of sacrifice. Many others have been inspired to broader action.

One morning, four tech workers who had become water activists showed up in a northern corner of the city where Mr. Srikantaiah, the water researcher, had worked with the local community to rejuvenate a once trash-strewn lake. A small network of gurgling filters and pipes sends out 200,000 liters of potable water per day.

“It will soon be 600,000,” Mr. Srikantaiah said. And the price per customer: nearly a third of what tanker drivers are charging.

The tech workers said they planned to share the details with neighbors and officials, to spread the word that a lake, using rainwater and lightly treated sewage, could be turned into a safe, affordable, reliable water source.

In an interview at his office, the chairman of the water board, Ram Prasath Manohar, 43, a seasoned government administrator installed three months ago, embraced the idea.

Acknowledging that some past officials had thought narrowly about water management, he said he hoped to attract public and private money for a more innovative approach, mixing data-driven methods that would revive lakes to let aquifers recharge and would expand rainwater harvesting and conservation.

“We’re going for a greener solution,” he said. “A more effective solution.”

So far, though, progress has been slow. He has not been able to hire any additional staff, he said, and he is working from 6 a.m. to 2 a.m. every day.

Short-term relief, he prays, will come in the next few weeks, with reservoir water extended to more parts of the city and the expected spring rains. Most of all, like many others in India’s Silicon Valley, he hopes all the public attention to water scarcity will add momentum for long-term change.

In one corner of his offices, a quote from Benjamin Franklin had been printed on a piece of paper and pasted to a window: “When the well is dry, we know the worth of water.”

“This crisis,” he said, rubbing his tired eyes, “it gives us an opportunity.”

Imran Khan Pathan contributed reporting.

Damien Cave is an international correspondent for The Times, covering the Indo-Pacific region. He is based in Sydney, Australia.  More about Damien Cave

Advertisement

IMAGES

  1. PHP Problem Solving Approach for Beginners (1/10)

    problem solving with php

  2. PHP Problem Solving Approach for Beginners (3/10)

    problem solving with php

  3. PHP Bonus

    problem solving with php

  4. 8 Steps For Effective Problem Solving

    problem solving with php

  5. What Is Problem-Solving? Steps, Processes, Exercises to do it Right

    problem solving with php

  6. 6 Ways to Improve Your Programming Problem Solving

    problem solving with php

VIDEO

  1. 1- Problem solving with php #001 Introduction and how to register in codeforces

  2. 24

  3. 13

  4. 4

  5. [Arabic] Problems Solving With PHP

  6. 26

COMMENTS

  1. 350+ PHP Practice Challenges // Edabit

    How Edabit Works. This is an introduction to how challenges on Edabit work. In the Code tab above you'll see a starter function that looks like this:function returnTrue() {}All you have to do is type return true; between the curly braces { } and then click the Check button. If you did this correctly, the button will turn red and say SUB ...

  2. PHP Exercises

    Exercises. We have gathered a variety of PHP exercises (with answers) for each PHP Chapter. Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.

  3. PHP Exercises, Practice, Solution

    PHP Exercises, Practice, Solution: PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

  4. 10 PHP Code Challenges for Beginners

    Code challenges are bite-sized development problems that you can solve with code. By solving code challenges, you'll build on your existing skills and learn new ones that'll help you efficiently solve more complex projects. And, with over 75% of websites using PHP today, adding this in-demand skill to your skill set is a no-brainer.

  5. PHP All Exercises & Assignments

    Here, you will find a list of PHP programs, along with problem description and solution. These programs can also be used as assignments for PHP students. Write a program to count 5 to 15 using PHP loop . Description: Write a Program to display count, from 5 to 15 using PHP loop as given below. ...

  6. PHP on Exercism

    The best part, it's 100% free for everyone. Join the PHP track. Develop fluency in 69 programming languages with our unique blend of learning, practice and mentoring. Exercism is fun, effective and 100% free, forever. Get fluent in PHP by solving 114 exercises. And then level up with mentoring from our world-class team.

  7. Practice Projects in PHP

    Computer Science • PHP • Web Development In this lesson, you've learned about conditionals—a fundamental yet powerful part of programming. Conditionals are so powerful, in fact, that they can be used to predict the future. In this project, you'll be creating a function that can answer any "yes" or "no" question. More guidance, 45 min.

  8. Full PHP CRASH Course

    The PHP CRASH Course is a comprehensive and hands-on course that covers all the essential concepts and features of PHP. It includes over 60 exercises that provide students with practical experience in writing PHP code. The course covers topics such as variables, operators, loops, functions, arrays, and more.

  9. How to Troubleshoot PHP Web Application Problems

    To view the errors in your PHP application, you will need to set the following settings in your PHP page so you can troubleshoot the problems. Knowing how to configure PHP display errors is really important. ini_set ('display_errors', 1); ini_set ('display_startup_errors', 1); error_reporting (E_ALL); This is usually at the top of a PHP web ...

  10. PHP (Basic)

    Basic. PHP is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. PHP stands for Hypertext Preprocessor, and is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. This key competency ...

  11. PHP basic

    4. Create a simple HTML form and accept the user name and display the name through PHP echo statement. Sample output of the HTML form : Click me to see the solution. 5. Write a PHP script to get the client IP address. Click me to see the solution. 6. Write a simple PHP browser detection script.

  12. PHP Challenges-1: Exercises, Practice, Solution

    For example given number is 59, the result will be 5. Input : 48 Output : 3 Step 1: 5 + 9 = 14 Step 1: 1 + 4 = 5 Click me to see the sample solution. 13. Write a PHP program to reverse the digits of an integer. Sample : x = 234, return 432 x = -234, return -432 Click me to see the sample solution. 14.

  13. PHP Interview Questions to Know

    The PHP interview process varies between organizations, but a few constants provide a broad picture of what to expect. These interviews are designed to assess a candidate's understanding of PHP as a language, its applications, problem-solving skills, and sometimes their experience with PHP-based frameworks like Laravel or Symfony.

  14. Learn by Doing: Practice PHP OOP (level 1)

    Exercise #1. In OOP class is like the blueprint and object are the instance. For example a house plan would be the class but the houses that will be construct base on that plan will be the objects. Your first challenge is to create a class name Product and create a instance of that class name product1.

  15. 5 problems a PHP developer can solve

    PHP makes sanitization tasks easier: It provides a native filter extension that developers can use to sanitize user data, ensuring it meets security requirements. It also has various useful functions for sanitization, such as the addslashes () function and the strip_tags () function. 5. Fixing any existing errors.

  16. 21 Essential PHP Interview Questions

    echo and print are largely the same in PHP. Both are used to output data to the screen. The only differences are as follows: echo does not return a value whereas print does return a value of 1 (this enables print to be used in expressions).; echo can accept multiple parameters (although such usage is rare) while print can only take a single argument.

  17. PHP Basic Algorithm

    PHP Basic Algorithm [136 exercises with solution] [An editor is available at the bottom of the page to write and execute the scripts. Go to the editor] 1. Write a PHP program to compute the sum of the two given integer values. If the two values are the same, then returns triple their sum. Sample Input 1, 2 3, 2 2, 2 Sample Output: 3 5 12

  18. problem-solving · GitHub Topics · GitHub

    Data structures and algorithms in PHP and JS. Random problem solving with the explanation. algorithms data-structures problem-solving Updated Nov 18, 2022; PHP; nihat-js / solve-math-expression-php Star 1. Code Issues Pull requests (5+5/2)+(5*4*2/2+7) without eval function ...

  19. 30 PHP Coding Interview Questions for Developers

    When preparing coding challenges for expert-level PHP engineers, you should pay attention to strong problem-solving skills, the design and architecture of the system and expertise in the framework. Some of the core areas for evaluating expert PHP programmers are advanced database interaction, performance optimization, security, CI/CD, cloud ...

  20. PHP Bonus

    BeeCrowd is one of the most popular online judge problem solving platform. It's suitable for both beginner, intermediate and advanced level users. ¶How we'll solve the problems ? We'll read the problems very carefully and solve those problems using PHP language. You can try with other language also if you're comfortable. We'll solve ...

  21. PHP arrays

    Write a PHP script to create a two-dimensional array (4x4), initialized to 10. Click me to see the solution. 57. Write a PHP function to compares two multidimensional arrays and returns the difference. Click me to see the solution. 58. Write a PHP script to combine (using one array for keys and another for its values) the following two arrays.

  22. How To Dump PHP Variables For Debugging In TextMate

    Setting Up Custom Bundles. Customize or create TextMate Bundles for PHP to include debugging snippets and commands. This allows for quick insertion of debugging functions. Open the Bundle Editor (Bundles > Edit Bundles). Choose the PHP bundle and create a new snippet with a shortcut for var_dump () or print_r ().

  23. Water Crisis in India's Silicon Valley

    Water being poured from a tanker truck in Bengaluru. "I get 50 calls a day" for water, said Prakash Chudegowda, a tanker driver. "I can only get to 15.". The Silicon Valley of South Asia ...

  24. PHP functions

    1. Write a function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument. Click me to see the solution. 2. Write a function to check whether a number is prime or not. Note: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

  25. PHP for loop

    PHP for loop [38 exercises with solution] [An editor is available at the bottom of the page to write and execute the scripts.Go to the editor] . 1. Create a script that displays 1-2-3-4-5-6-7-8-9-10 on one line. There will be no hyphen(-) at starting and ending position.