Top 30+ Basic PHP Interview Questions and Answers 2024

Spread the love

Below is a compilation of frequently asked basic PHP interview questions along with their corresponding answers. These PHP interview questions are applicable to newcomer professionals.

PHP, short for Hypertext Preprocessor, is a versatile programming language. Due to its high demand in web development, PHP professionals with expertise and experience are highly sought after by organizations. If you intend to embark on a career in this domain and get ready for a software or web developer interview, it is likely that your interview will encompass inquiries pertaining to PHP.

If you are looking for more advanced set of Questions, please have a look at “Top PHP Advanced Interview Questions and Answers

Table of Contents

Below are the important Basic PHP Interview Questions and answers for entry-level and candidates:

Q1. What is PHP?

PHP is an acronym for Hypertext Preprocessor. It is a web-oriented scripting language employed for generating dynamic and interactive web sites. It has the capability to execute any server-side programming job. A PHP file is composed of tags and has the “.php” extension. PHP code can be inserted into HTML code. Additionally, it can be employed in conjunction with web content management, frameworks, and template systems.

Q2. What is the correct and the most two common way to start and finish a PHP block of code?

The two predominant methods for initiating and terminating a PHP script are:

<?php 
// PHP code
?> 

// and 

<? 
// PHP code
?>

Q3. Explain the different types of data types in PHP.

#Data typeDescription
1IntegersIt includes whole numbers (without a decimal point).
2BooleansThese have only two possible values, either true or false.
3DoublesFloating-point numbers, like 23.6 or 2.32679.
4ArraysNamed and indexed collections of other values
5StringsSequences of characters
6ObjectsInstances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class
7NULLSpecial type that only has one value, NULL
8ResourcesSpecial variables that hold references to resources external to PHP

Q4. Is PHP a loosely typed language?

It is a loosely typed language, yes. You don’t have to declare a variable type in order to create a variable.

When you create a variable in PHP, you don’t have to worry about what kind of data will be stored in it. If you create a variable called $String, you don’t have to give it a string value. You can give it an integer value instead.

Such as:

$var = "Hello"; // String

$var = 20; // Integer

Q5. What is the difference between echo and print?

The echo method and the print method are both used to print the output in the browser. The echo method is faster than the print method and does not return any value after writing the output. It takes longer for the print method to work because it has to return the Boolean value after printing the result.

Syntax:

echo "PHP Developer";

$n = print "Java Developer";

Q6. How can we execute PHP script using the command line?

To run a PHP script, you use the PHP tool in the command line. You can use the file name, i.e. test.php as:

php test.php

Q7. How to declare an array?

There are three types of arrays that you can declare:

a. Numeric array b. Multidimensional array c. Associative array

<?php
// Numeric Array
$computer = ["Dell", "Lenovo", "HP"];

// Associative Array
$color = [
    "Sithi" => "Red",
    "Amit" => "Blue",
    "Mahek" => "Green"
];

// Multidimensional Array
$courses = [
    ["PHP", 50],
    ["VueJs", 15],
    ["Angular", 20]
];

Q8. Mention some of the constants in PHP and their purpose.

Here are a few constants:

a. _LINE_: The present numerical value indicating the position of the line within the file.

b. _FILE_: The term denotes the complete path and name of the file. When utilised within an include, it will provide the name of the included file.

c. _FUNCTION_: It provides the name of the function.

d. _CLASS_: The function retrieves the original class name as it was declared.

e. _METHOD_: It denotes the method employed by the class.

<?php
// a. __LINE__
echo 'This is line number ' . __LINE__ . "\n";

// b. __FILE__
echo 'This is the full path and filename: ' . __FILE__ . "\n";

// c. __FUNCTION__
function testFunction() {
    echo 'The function name is ' . __FUNCTION__ . "\n";
}

testFunction();

// d. __CLASS__
class TestClass {
    public function printClassName() {
        echo 'The class name is ' . __CLASS__ . "\n";
    }
}

$object = new TestClass();
$object->printClassName();

// e. __METHOD__
class TestMethodClass {
    public function printMethodName() {
        echo 'The method name is ' . __METHOD__ . "\n";
    }
}

$methodObject = new TestMethodClass();
$methodObject->printMethodName();
?>

Q9. Explain the uses of explode() and implode() functions.

Explode() Function:

The explode() function in PHP is used to split a string by a string. It returns an array of strings, each of which is a substring of the original string formed by splitting it on boundaries formed by the string delimiter.

Here’s an example:

<?php
$str = "Hello, how are you?";
$arr = explode(" ", $str);
print_r($arr);
?>

In this code, the explode() function splits the string $str into an array $arr at each space character. The print_r() function then prints the resulting array.

Implode() Function:

The implode() function in PHP is used to join array elements with a string. It returns a string from the elements of an array.

Here’s an example:

<?php
$arr = ['Hello,', 'how', 'are', 'you?'];
$str = implode(" ", $arr);
echo $str;
?>

In this code, the implode() function joins the elements of the array $arr into a string $str, with each element separated by a space character. The echo statement then prints the resulting string.

Q10. Explain the PHP $ and $$ variables ?

$ Variable

In PHP, a variable starts with the $ sign, followed by the name of the variable. The variable name is case-sensitive. Here’s an example:

<?php
$name = "John";
echo $name; // Outputs: John
?>

In this code, $name is a variable that holds the value “John”. The echo statement prints the value of $name.

$$ Variable

A double dollar $$ is a way to create dynamic variables in PHP. A variable variable takes the value of a variable and treats that as the name of a variable. Here’s an example:

<?php
$name = "John";
$$name = "Doe";
echo $John; // Outputs: Doe
?>

Q11. Explain the difference between GET and POST methods?

This is a frequently asked question in PHP interviews. There are two methods for transmitting data from a browser client to a web server:

a. The GET method: $_GET b. The POST method: $_POST

GET methodPOST method
The GET method creates a long string that shows up in the server log.The POST method does not impose any limitations on the size of data that can be sent.
The transmission is limited to a maximum of 1024 characters.This tool is capable of transmitting both binary data and ASCII data.
Transmitting binary data, such as word documents or photos, to the server is not supported.It is the HTTP protocol that makes this way safe, since the data sent by the POST method goes through an HTTP header.
The $_GET variable is used to get all the transmitted data through the GET method.$_POST associative array is provided by the PHP to access all the sent information using POST method

Q12. Explain type casting and type juggling.

Type Casting:

Type casting in PHP is used to change the data type of a variable. To cast a variable to a specific data type, you put the name of the data type in parentheses before the variable. Here’s an example:

<?php
$var = "10"; // string
$intVar = (int) $var;
echo gettype($intVar); // Outputs: integer
?>

In this code, $var is a string. (int)$var casts $var to an integer. gettype($intVar) then outputs the type of $intVar, which is “integer”.

Type Juggling:

Type juggling in PHP refers to PHP’s ability to change a variable’s type automatically based on the context in which it is used. Here’s an example:

<?php
$var = "10"; // string
$var += 2; // integer
echo gettype($var); // Outputs: integer
?>

In this code, $var is initially a string. However, when we use the += operator to add 2 to $var, PHP automatically changes $var’s type to integer to perform the operation. gettype($var) then outputs the type of $var, which is now “integer”.

Q13. What is the main difference between require() and require_once() ?

The main difference between require() and require_once() lies in their behavior of including files.

require() is a statement in PHP that is used to include a file in the script. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. Here’s an example:

<?php
require('somefile.php');
// Rest of the code
?>

In this case, ‘somefile.php’ will be included every time the require() statement is encountered.

On the other hand, require_once() is similar to require() but it checks if the file has already been included. If it has, it doesn’t include the file again. It is recommended when you want to include files where you have a lot of functions for example. This can help avoid problems such as function redefinitions, variable value reassignments, etc. Here’s an example

<?php
require_once('somefile.php');
// Rest of the code
?>

In this case, ‘somefile.php’ is included only once. If require_once() is called again later in the script for the same file, it will not be included again.

Q14. How to make a connection with MY SQL server ?

To establish a connection with a MySQL server in PHP, you can use the mysqli_connect() function. Here’s an example:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

In this code:

a. $servername is the name of your server. It’s usually “localhost” when the database is on the same server as your PHP script. b. $username and $password are the username and password to log into the MySQL server. c. $dbname is the name of the database you want to connect to. d. mysqli_connect() is the function that attempts to open a connection to the MySQL server. e. The if statement checks if the connection was successful. If mysqli_connect() returns false, mysqli_connect_error() will print the error message and die() will stop the PHP script.

Q15. What is the purpose of the var_dump() function in PHP ?

The var_dump() function in PHP is used for debugging purposes. It displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

Here’s an example:

<?php
$var = [1, 2, ["a", "b", "c"]];
var_dump($var);

// Output

array(3) {
    [0]=> int(1)
    [1]=> int(2)
    [2]=> array(3) {
        [0]=> string(1) "a"
        [1]=> string(1) "b"
        [2]=> string(1) "c"
    }
}
?>

Q16. Explain the difference between == and === in PHP ?

In PHP, == and === are both comparison operators, but they work slightly differently:

a. == is the equality operator. It checks if the values of the two operands are equal or not. If yes, then the condition becomes true. It does type coercion if necessary. For example:

<?php
$a = "100";
$b = 100;

var_dump($a == $b); // Outputs: bool(true)
?>

In this case, even though one is a string and the other is an integer, == returns true because it converts the string to a number before making the comparison.

b. === is the identical operator. It checks if the values of two operands are equal or not, and they are of the same data type. If yes, then the condition becomes true. Unlike ==, the === operator does not do type coercion. For example:

<?php
$a = "100";
$b = 100;

var_dump($a === $b); // Outputs: bool(false)
?>

In this case, === returns false because, although the values are the same, the types are different: one is a string and the other is an integer.

Q17. How can you prevent SQL injection in PHP ?

SQL injection is a code injection technique that attackers can use to insert malicious SQL statements into input fields for execution by the underlying SQL database. It’s a serious threat to web applications, and it’s important to protect against it. Here are some ways to prevent SQL injection in PHP:

  1. Use Prepared Statements (with Parameterized Queries): The parameters in prepared statements don’t need to be quoted; the driver automatically handles this. If an attacker attempts to include special characters in the parameter, it won’t affect the query. Here’s an example using MySQLi:
<?php
$conn = new mysqli('localhost', 'username', 'password', 'db');
$stmt = $conn->prepare('SELECT * FROM users WHERE email = ?');
$stmt->bind_param('s', $email); // 's' specifies the variable type => 'string'

$email = 'user@example.com';
$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Do something with $row
}
?>
  1. Use Stored Procedures: Stored procedures can encapsulate the SQL statements and treat all input as parameters.
  2. Escape User Input: If you can’t use prepared statements for some reason, you should at least escape user input using a function like mysqli_real_escape_string(). However, this is less secure than using prepared statements.
  3. Limit Privileges: Don’t give more privileges than necessary to the database user associated with the web application.
  4. Use a Web Application Firewall: A WAF can help filter out malicious data.

Q18. Explain the concept of sessions in PHP ?

In PHP, a session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the user’s computer but on the server. The session ends when the user closes the browser or after leaving the site, depending on the session timeout duration set on the server.

Here’s a basic example of how to use sessions in PHP:

<?php
// Starting a session
session_start();

// Storing session data
$_SESSION["username"] = "John Doe";

// Accessing session data
echo 'Hi, ' . $_SESSION["username"];

// Destroying session
session_destroy();
?>

In this example:

a. session_start() starts a new session or resumes an existing one. It’s typically the first thing in your PHP script. b. $_SESSION is an associative array containing session variables available to the current script. Here, we’re setting a session variable “username” to “John Doe”. c. You can access session variables just like you would any array. Here, we’re echoing the username stored in the session. d. session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.

Remember, session data is stored on the server, which makes it a safer option compared to cookies. However, it’s still important to ensure that you’re handling sessions securely to prevent session hijacking or session fixation attacks. For example, regenerate the session ID after login and logout, and avoid exposing session IDs in URLs.

Also, keep in mind that while sessions can store relatively large amounts of data compared to cookies, they are not intended to hold large amounts of data as it can affect your website’s performance. For large amounts of data, consider using a database or other methods of storage.

Sessions are a powerful tool for preserving state between page loads and are widely used in PHP applications for things like user logins, shopping carts, and more. They make your web applications smoother and more seamless to use.

Q19. Explain the concept of cookies in PHP ?

In PHP, a cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Here’s how you can set a cookie in PHP:

<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>

In this example, the setcookie() function is used to set a cookie. The arguments are the name of the cookie (“test_cookie”), the value of the cookie (“test”), the expiration time (in seconds), and the path where the cookie is available.

You can then retrieve the value of the cookie like this:

<?php
if(!isset($_COOKIE["test_cookie"])) {
    echo "Cookie named 'test_cookie' is not set!";
} else {
    echo "Cookie 'test_cookie' is set!<br>";
    echo "Value is: " . $_COOKIE["test_cookie"];
}
?>

In this case, $_COOKIE is a superglobal variable in PHP which is used to retrieve a cookie value. It’s an associative array and you can access the value of a cookie by passing the name of the cookie to the $_COOKIE array.

Remember, cookies are part of the HTTP header, so the setcookie() function must be called before any output is sent to the browser. This is the same limitation that the header() function in PHP has. Also, cookies are stored on the user’s computer, so they can be manipulated by the user, and thus can’t be trusted to store sensitive information.

Also, it’s important to note that cookies can be disabled on the client side, so they’re not always a reliable way to track a user’s session. For more reliable tracking, consider using sessions, which are server-side and thus more secure. However, cookies can be useful for things like remembering a user’s login information or other non-sensitive data between sessions.

Q20. What is the purpose of the header() function in PHP ?

The header() function in PHP is used to send a raw HTTP header to a client. It must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

Here are a few examples of how it can be used:

  1. Redirect the user to a different page:
<?php
header("Location: https://www.example.com");
exit;
?>

In this case, the header() function sends a Location header back to the client, instructing it to load a different URL.

  1. Set a cookie:
<?php
header('Set-Cookie: cookie_name=cookie_value');
?>

Here, the header() function is setting a cookie named cookie_name with the value cookie_value.

  1. Specify the type of content being returned:
<?php
header("Content-Type: application/json");
?>

In this example, the header() function is used to tell the client that the server will be returning JSON.

Remember, because header() modifies the HTTP headers, it must be called before any output is sent to the browser. If you try to call header() after output has been sent to the browser, PHP will throw an error. If you want to send a header after output has been sent, you’ll need to use output buffering.

Q21. How do you handle errors in PHP ?

Errors in PHP can be handled using the following methods:

a. die() or exit(): These functions can be used to stop the script and display an error message. For example:

<?php
if(!file_exists("welcome.txt")) {
  die("File not found");
} else {
  $file=fopen("welcome.txt","r");
}
?>

In this case, if the file “welcome.txt” does not exist, the die() function will stop the script and print “File not found”.

b. error_reporting(): This function sets the error reporting level. For example, to report all errors except notices, you can do:

<?php
error_reporting(E_ALL & ~E_NOTICE);
?>

c. try, catch, and finally blocks for exception handling: You can catch exceptions in PHP to handle them gracefully. For example:

<?php
try {
  // Code that may throw an exception
} catch (Exception $e) {
  // Code to handle the exception
} finally {
  // Code to be executed regardless of whether an exception was thrown
}
?>

d. Logging errors to a file using the error_log() function: This function sends an error message to the web server’s error log or to a file. For example:

<?php
error_log("Error message\n", 3, "/var/tmp/my-errors.log");
?>

In this case, “Error message” will be appended to the file “/var/tmp/my-errors.log”.

e. Custom error handling functions using set_error_handler(): This function allows you to define your own error handler. For example:

<?php
function customError($errno, $errstr) {
  echo "<b>Error:</b> [$errno] $errstr";
}

set_error_handler("customError");
?>

In this case, if an error occurs, PHP will call the function customError(), which will print the error level and message.

Q22. What is the purpose of the superglobals in PHP ?

Superglobals in PHP are built-in variables that are always available in all scopes. They provide a way to access information from the server, or about the current execution environment, from anywhere in a PHP script. Here are some of the most commonly used PHP superglobals:

Sure, here’s the information in a table format:

SuperglobalDescription
$_SERVERAn array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.
$_GETAn associative array of variables passed to the current script via the URL parameters.
$_POSTAn associative array of variables passed to the current script via the HTTP POST method.
$_FILESAn associative array of items uploaded to the current script via the HTTP POST method.
$_COOKIEAn associative array of variables passed to the current script via HTTP cookies.
$_SESSIONAn associative array containing session variables available to the current script.
$_REQUESTAn associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
$_ENVAn associative array of variables passed to the current script via the environment method.

Q23. How can you upload files in PHP?

In PHP, you can upload files using a form and the $_FILES superglobal. Here’s a basic example:

First, you need to create an HTML form that allows users to choose the file they want to upload:

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select file to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload File" name="submit">
</form>

In this form:

a. The enctype=”multipart/form-data” attribute is important when you’re using forms that have a file upload control. b. The input element with type=”file” allows the user to select the file.

Then, in the upload.php file, you can access the uploaded file through the $_FILES superglobal:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
  echo "The file ". htmlspecialchars(basename($_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
  echo "Sorry, there was an error uploading your file.";
}
?>

In this script:

  1. $_FILES[“fileToUpload”][“tmp_name”] contains the temporary location of the file on the server.
  2. $_FILES[“fileToUpload”][“name”] contains the original name of the file.
  3. move_uploaded_file() function moves the uploaded file to a new location ($target_file).

Q24. Explain the types and use of the different loops in PHP ?

Sure, PHP provides several ways to loop through data using different types of loops. Here are the most common ones:

  1. while: The while loop executes a block of code as long as the condition is true
<?php
$i = 1;
while ($i <= 5) {
  echo "The number is " . $i . "<br>";
  $i++;
}
?>
  1. do…while: The do…while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.
<?php
$i = 1;
do {
  echo "The number is " . $i . "<br>";
  $i++;
} while ($i <= 5);
?>
  1. for: The for loop is used when you know in advance how many times the script should run.
<?php
for ($i = 1; $i <= 5; $i++) {
  echo "The number is " . $i . "<br>";
}
?>
  1. foreach: The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
  echo "$value <br>";
}
?>

Q25. What is the purpose of the unset() function in PHP ?

The unset() function in PHP is used to destroy specified variables or array elements. After a variable has been unset, it is no longer set and it doesn’t hold any value.

Here’s an example of how you can use the unset() function:

<?php
$name = "John Doe";
echo $name; // Outputs: John Doe

unset($name);
echo $name; // Outputs: Notice: Undefined variable: name
?>

In this example, the unset() function destroys the $name variable. So, when you try to echo $name after it has been unset, PHP throws a notice saying the variable is undefined.

You can also use unset() to remove an element from an array:

<?php
$colors = array("red", "green", "blue", "yellow");
unset($colors[2]);
print_r($colors); // Outputs: Array ( [0] => red [1] => green [3] => yellow )
?>

In this case, unset($colors[2]) removes the third element (“blue”) from the $colors array.

Q26. Explain the purpose of the array_merge() function in PHP ?

The array_merge() function in PHP is used to merge one or more arrays into one array. The function appends the values of later arrays to the previous ones. It returns the resulting array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

Here’s an example:

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

// Output

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

As you can see, the “color” key from $array2 overwrote the “color” key from $array1. The integer keys were renumbered.

Note that array_merge() does not preserve numeric key values. If you need to preserve the numeric keys, use the + array union operator. However, the + operator will not overwrite the value of the “color” key in $array1 with the value from $array2.

Q27. What is the purpose of the file_get_contents() function in PHP ?

The file_get_contents() function in PHP is used to read a file into a string. This function is the preferred way to read the contents of a file into a string because it can use memory mapping techniques if supported by your OS to enhance performance.

Here’s a basic example of how to use file_get_contents():

<?php
$file = 'example.txt';

// Use file_get_contents to read the file's contents into a string
$data = file_get_contents($file);

echo $data;
?>

In this example, file_get_contents() reads the contents of ‘example.txt’ into the $data variable, which is then echoed out.

file_get_contents() returns the read data or FALSE on failure. It’s a simple and convenient way to read a file, an HTTP/FTP server, or other streams line by line into a string.

It’s also worth noting that file_get_contents() reads the entire file into memory at once, so for very large files, it might be more efficient to use fopen() in combination with fgets() or fread(). These functions read the file line by line or block by block, reducing the memory usage.

Q28. How do you use the array_push() function in PHP ?

The array_push() function in PHP is used to add one or more elements onto the end of an array. The function modifies the array in-place and returns the new number of elements in the array.

Here’s a basic example of how to use array_push():

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

In this example, “apple” and “raspberry” are pushed onto the end of the $stack array. The print_r($stack); statement would output:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

As you can see, “apple” and “raspberry” have been added to the end of the array. Remember, array_push() modifies the input array directly, so if you want to keep the original array unmodified, you should make a copy of it before using array_push(). Also, while array_push() can add multiple elements at once, if you’re only adding a single element, the [] syntax ($stack[] = "apple";) is more performant.

Q29. What is the use of the array_key_exists() function in PHP ?

The array_key_exists() function in PHP is used to check whether a specified key is present in an array or not. It returns true if the key is found in the array, and false otherwise.

Here’s a basic example of how to use array_key_exists():

<?php
$array = array("name" => "John", "age" => 25);

if (array_key_exists("name", $array)) {
  echo "Key 'name' exists in the array";
} else {
  echo "Key 'name' does not exist in the array";
}
?>

In this example, array_key_exists("name", $array) checks if the key “name” exists in the $array array. Since “name” is indeed a key in the array, the function returns true, and “Key ‘name’ exists in the array” is printed.

Remember, array_key_exists() only checks the keys of the array, not the values. If you want to check if a value exists in an array, you should use in_array(). Also, array_key_exists() will return true even if the value of the key is null.

Q30. In PHP, objects used are passed by value or passed by reference ?

In PHP, objects are passed by reference. This means that when you pass an object to a function, the function works with the original object, not a copy of the object. Any changes made to the object inside the function are reflected in the original object outside the function.

Here’s an example:

<?php
class TestClass {
  public $value = 'Original Value';

  public function changeValue($newValue) {
    $this->value = $newValue;
  }
}

$testObject = new TestClass();
echo $testObject->value; // Outputs: Original Value

$testObject->changeValue('New Value');
echo $testObject->value; // Outputs: New Value
?>

In this example, the changeValue() method of the TestClass object changes the value of the $value property. Because objects are passed by reference in PHP, this change is reflected in the $testObject object outside the method.

It’s important to note that while objects are passed by reference, basic data types (like integers, strings, and arrays) are passed by value. This means that a copy is made for those types, and changes made inside the function do not affect the original variable. If you want to change the original variable, you would need to pass it by reference using the & operator. For example, function changeValue(&$value) {...}.

Q31. What are the different PHP array functions ?

Some of the PHP array functions are mentioned below:

Array Functions

FunctionDescription
array()Creates an array
array_diff()Compares arrays and returns differences in values
array_reverse()Reverses an array
array_keys()Returns all the keys of the array
array_search()Searches a value and returns the corresponding key
array_reduce()Returns an array as a string, using a user-defined function
array_sum()Sums all the values of an array
array_push()Inserts one or more elements to the end of an array
array_pop()Deletes the last element of an array
array_replace()Replaces the values of the first array with the values from the following arrays
compact()Create an array containing variables and their values
current()Returns the current element in an array
end()Sets the internal pointer of an array to its last element
range()Creates an array containing a range of elements

Q32. Explain the use of break and continue statements.

Sure, break and continue are control structures in PHP that allow you to manipulate the flow of loops (for, foreach, while, do-while, and switch statements).

  1. break: The break statement is used to terminate the execution of the entire loop immediately. When a break statement is encountered inside a loop, the loop is immediately terminated, and the program control resumes at the next statement following the loop. It’s often used in conjunction with conditional statements (if). Here’s an example:
<?php
for ($i = 0; $i < 10; $i++) {
    if ($i == 5) {
        break;
    }
    echo $i;
}
?>

In this example, the loop will terminate as soon as $i equals 5, so the numbers 0 through 4 will be printed.

  1. continue: The continue statement is used to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration. It’s often used in conjunction with conditional statements (if). Here’s an example:
<?php
for ($i = 0; $i < 10; $i++) {
    if ($i == 5) {
        continue;
    }
    echo $i;
}
?>

In this example, when $i equals 5, the continue statement will be executed and the rest of the code for that iteration will be skipped. So, the numbers 0 through 4 and 6 through 9 will be printed.

Q34. Explain the difference between the functions strstr() and stristr().

Both strstr() and stristr() are PHP string functions used to find the first occurrence of a substring within a given string. Here’s how they differ

  1. strstr() is case-sensitive. It searches for the first occurrence of a string inside another string in a case-sensitive manner. For example, strstr("Hello World", "world") would not return a match because “world” (in lowercase) does not exactly match “World” (with an uppercase “W”) in the original string.
  2. stristr() is case-insensitive. It searches for the first occurrence of a string inside another string in a case-insensitive manner. So, stristr("Hello World", "world") would return a match because it ignores the case when comparing.
<?php
echo strstr("Hello World!", "world");  // Outputs: (nothing, because it's case-sensitive)
echo stristr("Hello World!", "world"); // Outputs: World!
?>

In both functions, if the substring is found, they return the part of the original string from the start of the substring. If the substring is not found, they return FALSE.