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
Accenture · PHP
Practice PHP questions specifically asked in Accenture interviews – ideal for online test preparation, technical rounds and final HR discussions.
Questions
73
Tagged for this company + subject
Company
Accenture
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 Accenture PHP round.
$_SERVER contains server and execution environment information like REQUEST_METHOD, PHP_SELF, and SERVER_NAME.
echo $_SERVER['PHP_SELF'];
PHP handles exceptions using try-catch blocks. Code that might fail goes in try, and the catch block handles the thrown exception.
try { throw new Exception('Error'); } catch(Exception $e) { echo $e->getMessage(); }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.
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 {}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 fetch method of PDOStatement retrieves the next row from the result set. It can return associative or numeric arrays depending on fetch mode.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
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 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 $_POST superglobal is used to collect form data sent using the POST method. It is safer for confidential data.
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';
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.
The array_sum function adds up all numeric elements of an array and returns the total.
array_sum([2,4,6]); // 12
Access modifiers control visibility. Public means accessible everywhere. Protected means within the class and subclasses. Private means only inside the same class.
class Test { public $a; protected $b; private $c; }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;Static properties and methods belong to the class itself, not to instances. You can access them using ClassName::method().
class Math { static $pi=3.14; static function add($a,$b){ return $a+$b; } }
echo Math::$pi;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'; } }A for loop includes three expressions: initialization, condition, and increment or decrement.
for($i=0; $i<5; $i++){ echo $i; }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();array_merge() joins arrays. If keys repeat, later values overwrite earlier ones for string keys.
$result = array_merge($a,$b);
In PHP, all variables begin with a dollar sign. For example, $name equals 'John'.
$name = 'John';
The echo statement outputs text or variables. It is faster than print and can take multiple arguments.
echo 'Hello World';
define() is used to create a constant that cannot be changed once declared. Example: define('PI', 3.14).
define('PI', 3.14);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');The fgets function reads a single line from an open file until it reaches a newline or end of file.
$line = fgets($handle);
The fclose function closes an open file handle and frees the system resources associated with it.
fclose($handle);
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.
A 404 status code indicates that the server cannot find the requested resource. It’s one of the most common response codes on the web.
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 Content-Type header tells the browser how to interpret the response data, such as text/html or application/json.
header('Content-Type: application/json');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();
Xdebug is a PHP extension used for debugging and profiling. It helps developers analyze script execution time and memory usage for performance optimization.
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' };Named arguments allow passing arguments to functions by name instead of position, improving code readability and allowing flexible argument ordering.
displayUser(age:25, name:'John');
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 }} @endifMiddleware filters HTTP requests entering your application. It’s often used for authentication, logging, and modifying requests or responses before reaching controllers.
php artisan make:middleware CheckUser
Escaping 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.
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.