1. Which superglobal provides information about headers, paths, and script locations?
$_SERVER contains server and execution environment information like REQUEST_METHOD, PHP_SELF, and SERVER_NAME.
echo $_SERVER['PHP_SELF'];
Get the Preplance app for a seamless learning experience. Practice offline, get daily streaks, and stay ahead with real-time interview updates.
Get it on
Google Play
4.9/5 Rating on Store
TCS · PHP
Practice PHP questions specifically asked in TCS interviews – ideal for online test preparation, technical rounds and final HR discussions.
Questions
74
Tagged for this company + subject
Company
TCS
View company-wise questions
Subject
PHP
Explore topic-wise practice
Go through each question and its explanation. Use this page for targeted revision just before your TCS PHP round.
$_SERVER contains server and execution environment information like REQUEST_METHOD, PHP_SELF, and SERVER_NAME.
echo $_SERVER['PHP_SELF'];
For complete preparation, combine this company + subject page with full company-wise practice and subject-wise practice. You can also explore other companies and topics from the links below.
The count() function returns the number of elements in an array or object implementing Countable.
count($arr);
implode() joins array elements into a string, and explode() splits a string into an array based on a delimiter.
$s = implode(',', $arr); $a = explode(',', $s);When a cookie is set with an expiry time in the past, the browser automatically removes it from storage, effectively deleting it.
setcookie('user','',time()-3600);The finally block always runs after try-catch, even if an exception is thrown. It's often used to close files or database connections.
try { } catch(Exception $e){ } finally { echo 'Done'; }The json_decode function converts a JSON string into a PHP array or object, making it easy to handle data from APIs or web services.
$arr = json_decode($json, true);
Each number in the Fibonacci sequence is the sum of the two preceding ones. After 5 comes 8 (3 + 5).
Prepared statements separate SQL logic from user input. This prevents attackers from injecting malicious SQL through form inputs or URLs.
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');The sort function arranges array elements in ascending order by value while reindexing the array numerically.
sort($arr);
PHP has several predefined superglobals like $_GET, $_POST, $_SERVER, $_SESSION, but there is no $_DATA variable.
The modulus operator (%) checks the remainder of division. If number % 2 equals zero, the number is even; otherwise, it's odd.
if($num % 2 == 0) echo 'Even';
If mysqli_connect fails, it returns false. You can check this and display an error using mysqli_connect_error.
if(!$conn){ echo mysqli_connect_error(); }In PHP, the 'extends' keyword allows one class to inherit properties and methods from another class. Example: class ParentClass {} class ChildClass extends ParentClass {}
class Vehicle {}
class Car extends Vehicle {}The break statement stops execution of the current case in a switch block. Without it, PHP continues to the next case.
switch($day){ case 'Mon': echo 'Work'; break; }The error_reporting() function sets which levels of errors PHP reports. For example, error_reporting(E_ALL) enables all errors.
error_reporting(E_ALL);
PHP arrays can be indexed using numbers, associative using keys, or multidimensional for nested data.
$arr = array('a','b'); $map = array('name'=>'John');Constructor property promotion simplifies class definitions by allowing properties to be defined and assigned directly in the constructor parameter list.
class User { function __construct(public string $name, private int $age){} }The bind_param function binds PHP variables to the SQL query placeholders before execution. It helps ensure secure and structured queries.
$stmt->bind_param('s',$name);The error_log() function sends error messages to a log file or email for debugging without displaying them to users.
error_log('Database connection failed');trigger_error() allows you to create custom warning or notice messages in PHP code. Useful for debugging or enforcing logic.
trigger_error('Invalid input', E_USER_WARNING);MySQLi stands for MySQL Improved. It allows PHP scripts to connect and interact with MySQL databases securely and efficiently.
$conn = mysqli_connect('localhost','root','pass','test');The __construct() method is called automatically when a class object is created. It is used to initialize values. Example: class Car { function __construct(){ echo 'Car ready'; } }
class Car {
function __construct(){ echo 'Object created'; }
}The session_start function initializes or resumes a session. It must be called before any output is sent to the browser to enable PHP to use session variables.
session_start();
in_array() searches for a value in an array and returns true if found, false otherwise.
in_array('apple', $fruits);The GET method appends form data to the URL, making it visible in the address bar. It is used for non-sensitive data requests.
The $_FILES array stores information about uploaded files like name, type, size, and temporary location.
echo $_FILES['myfile']['name'];
session_start() initializes session tracking in PHP. It must be called before any output is sent.
session_start(); $_SESSION['user']='John';
To delete a cookie, set it again with an expired time using setcookie. PHP has no delete_cookie() function.
setcookie('user','',time()-3600);The strrev function reverses the order of characters in a string and returns the reversed string.
echo strrev('Hello'); // olleHA palindrome string remains the same when reversed, such as level or madam. Checking this is a common PHP coding test question.
PHP has several error types such as Parse Error, Notice, Warning, and Fatal Error. 'Null Error' is not a real PHP error type.
PHP supports two syntaxes for if statements. The standard uses braces, and the alternate syntax uses a colon with endif for template files.
if ($x > 10) { echo 'Big'; }
// or
if ($x > 10): echo 'Big'; endif;An interface defines a set of methods that must be implemented by any class using it. It helps in achieving multiple inheritance in PHP.
interface Animal { public function sound(); }
class Dog implements Animal { public function sound(){ echo 'Bark'; } }Traits allow code reusability in multiple classes. They provide a way to use common methods across unrelated classes.
trait Logger { function log(){ echo 'Logging...'; } }
class App { use Logger; }In do-while, the body runs once before checking the condition. In while, the condition is checked first.
do { echo $x; $x++; } while ($x < 5);mysqli_fetch_assoc fetches one row from the result set and returns it as an associative array where column names are used as keys.
$row = mysqli_fetch_assoc($result);
Functions are declared using the keyword function, followed by a name and parentheses.
function greet(){ echo 'Hello'; }You can assign a default value using an equal sign in the parameter list. Example: function add($a=10).
function greet($name='User'){ echo $name; }array_key_exists() checks if a key exists in an array. isset() also works but returns false for null values.
array_key_exists('name', $user);substr() extracts part of a string from a start position and optional length.
substr('Hello',1,3); // ellIn PHP, the keyword 'class' is used to define a class, and 'new' is used to create an object from that class. Example: class Car { public $name; } $car = new Car();
class Car { public $brand; }
$car = new Car();Arrays can be created using the array() function or square brackets from PHP 5.4 onward.
$a = array(1,2,3); $b = [1,2,3];
PHP originally stood for Personal Home Page, but now it means PHP Hypertext Preprocessor. It is a recursive acronym and used mainly for server-side scripting.
PHP allows single-line comments using double slashes or a hash. Multiline comments use slash star and star slash.
// comment or # comment
The echo statement outputs text or variables. It is faster than print and can take multiple arguments.
echo 'Hello World';
PHP variable names are case-sensitive. $Name and $name are different variables. However, function names are not case-sensitive.
PHP superglobals are built-in variables accessible anywhere. Examples include $_POST, $_GET, $_SESSION, $_SERVER, and $GLOBALS.
The throw keyword is used to manually generate an exception in PHP. It is followed by an Exception object.
throw new Exception('Invalid input');The fopen function opens a file in the specified mode such as read, write, or append. It returns a file handle used for further operations.
fopen('data.txt','r');Using mode 'a' opens the file for writing at the end. The pointer moves to the end and preserves existing content.
fopen('log.txt','a');The fwrite function is used to write data to an open file. If the file is not writable, it returns false.
fwrite($handle,'Hello');
file_get_contents reads the entire file content into a single string, making it a simple way to load small files.
$data = file_get_contents('info.txt');The file_exists function checks if a given path refers to an existing file or directory and returns true or false.
if(file_exists('data.txt')) { echo 'Found'; }The session_destroy function removes all session data stored on the server. It is often used during logout to clear the user’s session.
session_destroy();
REST is an architectural style for designing APIs that use standard HTTP methods like GET, POST, PUT, and DELETE for communication between client and server.
The PUT method is used to update or replace an existing resource on the server. It is idempotent, meaning multiple identical requests produce the same result.
cURL is a PHP library used to send and receive HTTP requests. It helps in communicating with APIs, external services, and web servers programmatically.
$ch = curl_init('https://api.example.com');The header function sends raw HTTP headers to the browser before any output. It’s commonly used for redirection and setting content type.
header('Location: login.php');Namespaces help organize code and prevent conflicts between classes or functions with the same name. They are especially useful in large applications and libraries.
namespace MyApp\Controllers;
Composer is PHP’s dependency manager. It automatically downloads and installs external libraries and manages their versions for your project.
composer install
The memory_limit directive in php.ini defines the maximum amount of memory a single PHP script can use, preventing memory overflows.
ini_set('memory_limit','256M');Output buffering temporarily holds the output before sending it to the browser. It allows manipulation of headers or compression of data before output.
ob_start(); echo 'Hello'; ob_end_flush();
JIT, or Just in Time compilation, improves performance by compiling PHP bytecode into native machine code during execution, reducing interpretation overhead.
The match expression compares a value against multiple conditions like switch, but it returns a value, supports strict comparison, and doesn’t require break statements.
echo match($status){ 200 => 'OK', 404 => 'Not Found', default => 'Error' };Service Providers bootstrap application services like event listeners, middleware, and routes. They register bindings and configurations during app startup.
The mixed type allows a variable or function to accept any type, including int, float, string, array, object, or null. It’s useful for flexible APIs.
function processData(mixed $data){ return $data; }A WeakMap stores object references as keys without preventing them from being garbage collected, improving memory efficiency in complex systems.
$map = new WeakMap();
Laravel is a popular open-source PHP framework designed to simplify web application development using the MVC architecture and elegant syntax.
Artisan is Laravel’s command-line interface. It automates repetitive tasks such as creating controllers, models, and migrations, and running maintenance commands.
php artisan make:controller UserController
Eloquent is Laravel’s Object-Relational Mapper that simplifies database interactions by representing tables as models with expressive query methods.
User::where('active',1)->get();Blade is Laravel’s powerful templating engine that allows embedding PHP code in HTML cleanly using simple syntax. It supports layouts, loops, and conditionals.
@if($user) Welcome, {{ $user->name }} @endifEscaping output ensures user input is shown as plain text instead of executable HTML or JavaScript. This prevents Cross-Site Scripting attacks.
echo htmlspecialchars($input, ENT_QUOTES);
Using HTTPS encrypts session data in transit, while regenerating session IDs after login prevents attackers from reusing old session tokens.
session_regenerate_id(true);
The .env file contains sensitive information like API keys and database credentials. It should never be shared or committed to version control.