1. Which function returns the number of elements in an array?
The count() function returns the number of elements in an array or object implementing Countable.
count($arr);
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
Cognizant · PHP
Practice PHP questions specifically asked in Cognizant interviews – ideal for online test preparation, technical rounds and final HR discussions.
Questions
55
Tagged for this company + subject
Company
Cognizant
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 Cognizant PHP round.
The count() function returns the number of elements in an array or object implementing Countable.
count($arr);
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.
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);file_put_contents writes data to a file in one call. If the file does not exist, it creates it automatically.
file_put_contents('info.txt','Hello World');PDO stands for PHP Data Object. It provides a database abstraction layer that works with many database systems like MySQL, SQLite, and PostgreSQL.
$pdo = new PDO('mysql:host=localhost;dbname=test','root','pass');The factorial of a number is the product of all positive integers up to that number. So 5 factorial equals 5 × 4 × 3 × 2 × 1, which is 120.
OPCache improves performance by storing precompiled PHP bytecode in memory, reducing the need for PHP to parse and compile scripts on every request.
PHP’s garbage collector automatically frees memory by removing objects and variables that are no longer referenced, improving efficiency.
gc_collect_cycles();
The nullsafe operator prevents runtime errors when accessing methods or properties on null objects by returning null instead of throwing an error.
$user?->getProfile()?->getName();
The str_contains function returns true if one string is found within another. It replaces the need for using strpos with manual comparison.
str_contains('Hello World','World');All web routes that respond to HTTP requests in Laravel are typically defined in the routes/web.php file using simple route definitions.
Route::get('/home', [HomeController::class, 'index']);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';
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);
Method overriding means redefining a parent class method inside a child class with the same name and parameters. The child version replaces the parent one when called from the child object.
class ParentClass { function greet(){ echo 'Hi'; } }
class Child extends ParentClass { function greet(){ echo 'Hello'; } }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 $_SESSION superglobal holds data for the current session, allowing values to be shared across different pages for the same user.
$_SESSION['user'] = 'John';
The $_COOKIE superglobal is used to access cookie values that have been sent from the browser back to the server.
echo $_COOKIE['user'];
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 GET method appends form data to the URL, making it visible in the address bar. It is used for non-sensitive data requests.
$_REQUEST collects data from both $_GET and $_POST depending on PHP configuration. It is used for flexible form handling.
setcookie() is used to send a cookie from the server to the client. Cookies store small data on the user's browser.
setcookie('user','John',time()+3600);To delete a cookie, set it again with an expired time using setcookie. PHP has no delete_cookie() function.
setcookie('user','',time()-3600);The count function returns the total number of elements in an array or the number of properties in an object.
count([1,2,3,4]); // 4
$this refers to the current object instance inside a class. It is used to access class properties or methods of that object.
class User { public $name; function say(){ echo $this->name; } }A while loop checks the condition first, then executes the body. A do-while loop executes once before checking.
while($x < 5){ echo $x; $x++; }The mysqli_query function sends a query to the MySQL server and returns a result object for SELECT or true for successful INSERT, UPDATE, or DELETE operations.
$result = mysqli_query($conn,'SELECT * FROM users');
The foreach loop is made for iterating arrays. It can loop through both keys and values easily.
foreach($arr as $val){ echo $val; }Prepared statements increase performance by precompiling SQL and prevent SQL injection by separating query structure from user data.
$stmt = $pdo->prepare('SELECT * FROM users WHERE id=?');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; }strlen() returns the number of characters in a string, including spaces.
strlen('Hello');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];
In PHP, all variables begin with a dollar sign. For example, $name equals 'John'.
$name = 'John';
PHP does not have a specific 'character' type. A single character is treated as a string of length one.
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 Exception class is the base for all exceptions. You can create your own exceptions by extending it.
class MyError extends Exception {}Custom exceptions are created by extending PHP’s built-in Exception class and overriding its methods if needed.
class MyException extends Exception { }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');
The unlink function deletes a file from the file system. It returns true on success or false on failure.
unlink('old.txt');By default, PHP stores session data as temporary files on the server in a directory defined by the session.save_path configuration in php.ini.
Authentication verifies the identity of a user, ensuring that the person logging in is who they claim to be before granting access to protected areas.
The json_encode function converts PHP data structures like arrays or objects into JSON strings, which can be sent over APIs or stored easily.
json_encode($data);
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.
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');Autoloading allows PHP to automatically include the required class file when an object is created. It removes the need for manual include statements.
spl_autoload_register(function($class){ include $class.'.php'; });Union types let you declare that a parameter or return value can accept multiple types, such as int or float. It improves type safety and flexibility.
function sum(int|float $a, int|float $b){ return $a+$b; }Service Providers bootstrap application services like event listeners, middleware, and routes. They register bindings and configurations during app startup.
Attributes allow developers to add structured metadata to classes, methods, or properties. They can be read using reflection for configuration or annotations.
#[Route('/home')] class HomeController {}A CSRF token is a random, unique value added to each form or request. The server verifies it to ensure the request came from a trusted source, preventing forgery attacks.
MVC stands for Model View Controller. It separates data handling (Model), presentation (View), and business logic (Controller) for better organization and maintainability.
Migrations are version control for your database. They allow you to create, modify, and share database structures across different environments easily.
php artisan make:migration create_users_table
The password_hash function automatically salts and hashes passwords using strong algorithms like bcrypt, making stored passwords secure.
password_hash('mypassword', PASSWORD_DEFAULT);In production, sensitive error messages should not be visible to users. Instead, errors should be logged securely for developers to review later.
ini_set('display_errors',0); ini_set('log_errors',1);API keys are unique identifiers used to authenticate and track client access to an API. They help control usage and prevent unauthorized access.