Interview-Questions-Img

PHP Interview Questions and Answers 2024

Find the list of top PHP interview questions and answers for both freshers and experienced professionals.

Interview Questions

PHP is a script-based web programming language that allows developers to create both static and dynamic web pages. An open-source and free-to-use language, PHP can be used for creating, opening, editing, and deleting files from the server. 

Some of the most important roles of PHP language include processing cookies, modifying data in the database, data encryption, collection of data from forms, etc. 

It supports many databases like MySQL, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.

PHP stands for Hypertext Preprocessor.

PHP was previously known as Personal Home Page.

PHP syntax resembles Perl and C.

The PHP latest version (as of April 2022) is 8.1.5.

Zend Engine 2 is the scripting engine that powers PHP.

Following are the main purposes and roles of PHP language:

  • It is a script-based web language that allows developers to create dynamic web pages.

  • It gets data from forms and uses it to create dynamic page content.

  • It can work with databases, send and receive cookies, and send emails, among other things.

  • Create, edit, and delete database content.

  • It can restrict a user's ability to access a web page.

PEAR means "PHP Extension and Application Repository."

PEAR is a reusable PHP component framework and distribution system. It includes PHP snippets as well as a library for reusing the code. It has a command-line interface that can be used to install packages. It is a PHP extension that allows web developers to program at a higher level.

A static website means the content on the web pages is stable and the same for every user browsing it. It is built using HTML, CSS, and JavaScript. 

On the other hand, the content on dynamic websites can change on the basis of user behaviour. It allows the website owners to sever specific content or modified content for different users. Dynamic websites are usually built using PHP, NodeJS, ASP.NET, etc.

PHP4 does not support the OOPS concept and relies on the Zend Engine 1. Whereas PHP5 uses Zend Engine 2 and supports the OOPS concept.

These are the most preferred frameworks of PHP:

  • CakePHP

  • CodeIgniter

  • Yii 2

  • Symfony

  • Zend Framework

Below is a list of primary PHP 7 features:

  • Scalar type declarations

  • Return type declarations

  • Null coalescing operator (??)

  • Spaceship operator

  • Constant arrays using define()

  • Anonymous classes

  • Closure::call method

  • Group use declaration

  • Generator return expressions

  • Generator delegation

  • Space ship operator

Use the PHP command-line interface (CLI) and enter the following as the file name of the script to run:

php script.php

The PHP code always starts with . The block of PHP code are:

To run a PHP program from the command line, follow these steps:

  • Open a terminal window.

  • Go to the specified folder or directory containing PHP files.

  • Then, using the command php file name.php, we can run PHP code.

  • To test the PHP code, start the server with the command php -S localhost:port -t your folder/ to test the PHP code.

We can show the text in PHP script by using echo and print statements.

Example of displaying text in PHP with echo statement:

echo "

Let’s go through PHP interview questions

";

echo "Hello world!
";

echo "I’ll crack my PHP interview for sure
";

?>

Output:

Let’s go through PHP interview questions

Hello world!

I’ll crack my PHP interview for sure

Example of displaying text in PHP with print statement:

print "

Most Important Interview Questions on PHP

";

print "Hello world!
";

print "I’m on my way to crack PHP interview!";

?>

Output:

Most Important Interview Questions on PHP

Hello world!

I’m on my way to crack PHP interview!

PHP is case-sensitive to some extent. It means that variable names are case sensitive, but function names are not, i.e., user-defined functions are case insensitive.

Variables are used to store values or data in a program to be utilised later. Variable declaration and storage are handled differently in PHP. The following are the characteristics of the variables:

  • Declare a variable with a dollar sign ($) before the variable name in PHP.

  • The name of a variable contains alphanumeric characters and underscores (for example, 'a-z', 'A-Z', '0-9', and ' ').

  • A letter or underscore must precede the variable name, not a number.

  • PHP is a loosely typed language. We don't need to declare the data types of variables. Instead, PHP infers them from the values.

  •  PHP variables are important. $sum and $SUM are handled differently.

The define() function defines and retrieves a constant's value. A PHP constant is an identifier with a fixed value that does not change over time. A continuous can never be changed or undefined once it has been defined. The $ symbol is not used with a constant.

These are the most popular content management systems built using PHP:

WordPress: It is a free and open-source Content Management System (CMS). It's the most popular CMS being used by nearly 44% of the total websites.

Joomla: It is another open-source CMS for publishing content. It is based on the model-view-controller (MVC) web application framework, which can be used independently.

Magento: It is an open-source platform for developing eCommerce websites.

Drupal: It is a PHP-based CMS platform distributed under the GNU (General Public License).

The break statement ends a loop's iteration immediately, and the program control returns to the next statement after the loop.

The continue statement skips the iteration that is currently running and jumps to the next one. The continue 2 acts as a case terminator, bypassing the current loop iteration. 

Comments are used to prevent the statement from being executed. The compiler disregards it. Single-line comments and multi-line comments are the two types of comments in PHP.

  • A single-line comment is preceded by a double forward-slash (//).

  • Analysis with multiple lines: The words are within the /* comment section */.

To count the number of elements in an array, use PHP's count() function. If the variable has been set to an empty array, the procedure may return 0. The process also returns 0 for variables that aren't fixed.

The four types of loops supported by PHP are listed below:

  • for loop

  • while loop

  • do-while loop

  • foreach loop

  • The for loop is thought to be openly executing the iteration, whereas each loop hides the iteration and makes it more visible.

  • Compared to the for loop, the foreach loop is thought to perform better.

  • Although the foreach loop iterates over an array of elements, the execution is simplified, and the loop is completed in less time than the for loop.

  • Because the foreach loop allocates temporary memory for index iterations, the overall system's memory allocation performance is redundant.

Run the PHP CLI with the -a option as follows:

php -a

The two most common ways to begin and end a PHP script:

  and <? [--- PHP code ---] ?>

We must use the unique tags and ?> to be able to display the output directly to the browser.

Many new OOP (Object Oriented Programming) features are available in PHP 5. These primarily differentiate between the PHP versions 4 and 5. 

Some of the primary features in PHP 5 are:

  • Robust Support for Object-Oriented Programming

  • A Completely Rewritten MySQL Extension

  • A Suite of Interoperable XML ToolS

  • Cleaner Error Handling with Exceptions

PHP only supports single inheritance, which means that it can extend a class by using the keyword 'extended' from only one other class.

In PHP5, the term 'final' is used first. The term "final class" refers to a class that cannot extend or a method that cannot override.

We use the operator ' = =' to see if two objects are instanced from the same class and have the same attributes and values; we use the operator '=='. The identity operator '===' can be used to see if two objects refer to the same instance of the same class.

PHP scripts can generate HTML and communicate with it.

  • PHP is a programming language, while HTML is a markup language.

  • PHP code runs on the server, whereas HTML code is parsed by the client browser.

  • PHP generates dynamic web pages, whereas HTML generates static web pages.

  • PHP can connect to a database, but HTML cannot connect to a database.

  • PHP is difficult to learn and use, while HTML is simple to learn and use.

If we want to pass values through a form or a URL, we must use htmlspecialchars() and urlencode to encode and decode them ().

The GD library is required to run image functions.

Depending on the image formats to work with, GD and PHP may additionally require other libraries. The image functions in PHP can be used to determine the size of JPEG, GIF, PNG, SWF, TIFF, and JPEG2000 pictures.

image types() return the supported image formats and styles in the current version of GD-PHP.

getimagesize() returns the size, imagesx() returns the width, and imagesy() returns the height.

The function require() throws a fatal error if it cannot access the file. The include() function, on the other hand, issues a warning, and the PHP script continues to run.

The only difference between require() and require once() is that the second function checks if the PHP script is already included before executing it.

 

(Include once() and include() work in the same way.)

There are two options:

<!--?php echo "Method 1"; 

print "Method 2"; ?-->

 

To display a human-readable result, use the print r function().

At the start of a script, the set time limit(0) directive sets the execution time to infinite to avoid the PHP error maximum execution time exceeded.' You can also specify it in the php.ini configuration file.

This is a PHP syntax error indicating that a mistake on line x prevents the program from parsing and running.

file_get_contents() allows you to read a file and save its contents to a string variable.

To connect to a MySQL database, we must use the mysqli_connect() function, which looks like this:

<!--?php $database = mysqli_connect("HOST", "USER_NAME", "PASSWORD"); mysqli_select_db($database,"DATABASE_NAME"); ?-->

MySQL connect() maintains a persistent database connection, which means the connection does not close when the PHP script terminates.

In PHP 7.0 and higher, this function is not supported.

We can use mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object, or mysqli_fetch_row to manage the Mysql result set.

A result set's number of rows is returned by the function mysqli_num_rows().

The number of rows affected by a SQL query is returned by mysqli_affected_rows().

The mysqli_fetch_object() returns the first single matching record, whereas mysqli_fetch_array() returns an array of all matching records from the table.

We use the $_GET array to access data sent via the GET method, as shown below:

www.url.com?var=value

$variable = $_GET["var"]; this will now contain 'value'

The $_POST array is used to access the data sent this way.

If you have a form field called 'var' on the form, and the user submits the posting form, you can get the value as follows:

$_POST["var"];

Whether something is a number or not, use the dedicated function is_numeric().

To determine whether a value is an alphanumeric value, use the dedicated function ctype_alnum.

The empty() function can be used to check whether a variable has a value or not.

The unlink() function is used to handle file systems. It simply deletes the specified file.

The unset() function handles variable management. It will undefine a variable.

We can use the addslashes function to escape data before storing it in the database.

The stripslashes function allows us to remove escape characters from a string before apostrophes.

In the PHP configuration file, we must enable the Magic quotes entry.

The function get_magic_quotes_gpc() determines whether or not magic quotes are enabled.

The strip_tags() function allows us to remove HTML tags from a string.

A static variable is only defined once within a function, and its value can be changed during function calls as follows:

<!--?php function testFunction() { static $testVariable = 1; echo $testVariable; $testVariable++; } testFunction(); //1 testFunction(); //2 testFunction(); //3 ?-->

The global keyword can be used to enable this feature.

The instruction'return $value;' causes a function to return a value.

Instead of using the standard hashing algorithms such as md5, sha1, or sha256, which are conceived to be fast, It's better to use crypt(), which comes with many hashing algorithms built-in, or hash(), which offers more options than crypt() (). As a result, using these techniques to hash passwords can leave them vulnerable.

The PHP-OpenSSL extension supports several cryptographic operations, including digital signature generation and verification.

The define() directive allows us to define a constant in the following way:

define ("ACONSTANT", 123);

We use an ampersand in front of a variable to pass it by reference, as shown below:

$var1 = &$var2

PHP casts everything to the integer type, "13" and 12 can be compared.

Before the variable is cast, the name of the output type must be specified in parentheses as follows:

* (int), (integer) – cast to integer

* (bool), (boolean) – cast to boolean

* (float), (double), (real) – cast to float

* (string) – cast to string

* (array) – cast to array

* (object) – cast to object

When the original if was replaced with: and the code block was written without braces.

It is made up of three expressions: a condition and two operands that describe If the condition is true or false, and which instruction should be executed:

Expression 1? Expression 2 is the same as Expression 3.

The Parameters passed into a function is returned by the function func_num_args().

Access static functions that don't require object initialization with  ::

__wakeup retrieves all the variables that need to be saved, while __sleep returns the array of all the variables that need to be kept.

Objects are passed by reference in PHP.

Parent :: constructor($value)

It is a logical object that allows us to perform certain tasks. A session keeps temporary data between PHP pages.

The function session_start() is used to activate a session.

Cookies or URL parameters can be used to propagate a session id.

A persistent cookie is stored in the browser's cookie file indefinitely. Cookies are temporary by default and are deleted when we close the browser.

When the PHP script is finished, the sessions are automatically deleted, but can be manually removed with the session_write_close().

The session_unregister() function frees all session variables while the  session_unset() function unregisters a global variable from the current session.

$GLOBALS is an associative array containing all variable references currently defined in the script's global scope.

The $_SERVER array contains data generated by the webserver, such as paths, headers, and script locations.

The associative array $_FILES contains things submitted to the current script using the HTTP POST method.

The error code for the uploaded file is stored in $_FILES['userfile'] ['error']. 

We can change the maximum file size that can be uploaded by changing upload_max_filesize in php.ini.

The environment method sends an associative array $_ENV of variables to the current PHP script.

$_COOKIE is a variable array sent as an associative array via HTTP Cookies to the current PHP script.

The variable scope is the context in which it is defined. All PHP variables, for the most part, have only one scope. This single scope includes both included and required files.

Let’s understand the difference between these operators with an example:

$a and $b: TRUE if both $a and $b are TRUE.

$9a & $b: Bits that are set in both $a and $b are set.

The concatenation operator ('.') is the first, and it returns the right value and left arguments concatenated. The second is ('.='), which appends the right-hand to the left-hand argument.

$a === $b, if $a and $b have the same key/value pairs in the same order and of the same types, then TRUE.

We use instanceof to check whether a PHP variable is an instantiated object of a specific class.

The goto statement can be used to navigate through the PHP program. A goto statement is followed by the desired target label in the instruction. and a title followed by a colon points to the target.

Exception ::__toString returns the exception's string representation.

The function parse_ini_file() allows us to load an init file named filename and return the settings in an associative array.

We can use the isset boolean function to check whether a variable is set and not NULL.

The strstr(string allString, string occ) function returns a portion of allString from the first occurrence of occ to the end of allString. The case of this function matters. The only difference between stristr() and strstr() is that stristr() is case insensitive.

‘for’ can be written as follows:

for (expr1; expr2; expr3)

statement

At the start, the first expression is run once. expr2 is evaluated after each iteration. The loop continues if it is TRUE, and the statements inside are executed. If it returns FALSE, the loop will be terminated. At the end of each iteration, expr3 is evaluated.

Foreach, on the other hand, is a simple way to iterate over arrays and is only used with arrays and objects.

The document.form class can be used.

To submit the form, use the submit() function. For example:

The function eregi_replace() is identical to ereg_replace() except that when matching alphabetic characters, it ignores case distinction.

Yes, we use the urlencode() function to protect special characters.

Warnings (serious errors), notices (non-critical errors), and fatal errors are the three types of errors (critical errors).

Sessions, cookies, and hidden form fields can all be used to pass variables between PHP pages.

We can extend the execution time of a PHP script by using the set_time_limit(int seconds) function. Thirty seconds is the default time limit.

Yes. The cookie can be deleted by setting it to expire in the past.

In PHP, the default session time is until the browser is closed.

Yes, (Distributed) Component Object Model components ((D)COM) can be used in PHP scripts that are provided as a framework.

You can update PHP if it changes By Memcached:

  • Clearing the Cache Proactively: The Cache is cleared when an insert or update is made.

  • Resetting the Cache: This method is similar to the first, except instead of deleting the keys and waiting for the following data request to refresh the Cache, the values are reset after the insert or update.