🧩 Explain array – related functions in PHP
1. Array Creation and Checking
Function Description Example
array() Creates an array. $arr = array(1, 2, 3);
range($start, $end, Creates an array with a range of range(1, 5) → [1, 2, 3,
$step) elements. 4, 5]
is_array($var) Checks if a variable is an array. is_array($arr) → true
🔍 2. Array Information and Counting
Function Description Example
count($array) Counts all elements in an array. count([1,2,3]) → 3
sizeof($array) Same as count(). sizeof([1,2,3]) → 3
array_count_values($array)
Counts all values and returns an [“a”, “b”, “a”] →
associative array. ["a"=>2, "b"=>1]
🧭 3. Accessing Keys and Values
Function Description Example
array_keys($array) Returns all keys. ["a"=>1,"b"=>2] → ["a","b"]
array_values($array) Returns all values. ["a"=>1,"b"=>2] → [1,2]
array_key_exists($key, $array) Checks if a key exists. array_key_exists("a", $arr)
4. Adding, Removing, and Modifying Elements
Function Description Example
array_push($array, $val1, Adds elements to the $arr = [1,2];
$val2, ...) end. array_push($arr,3); → [1,2,3]
Removes the last
array_pop($array) [1,2,3] → [1,2]
element.
Removes the first
array_shift($array) [1,2,3] → [2,3]
element.
array_unshift($array, $val1, Adds elements to the
$val2, ...) [2,3] → [1,2,3]
beginning.
Removes an element
unset($array[$key]) Removes specific value.
by key.
🧮 5. Sorting Arrays
Function Description Example
Sorts values in ascending order
sort($array) [3,1,2] → [1,2,3]
(reindexes keys).
rsort($array) Sorts in descending order. [1,2,3] → [3,2,1]
["b"=>2,"a"=>1] →
asort($array) Sorts by value, preserves keys. ["a"=>1,"b"=>2]
ksort($array) Sorts by key (ascending). ["b"=>2,"a"=>1] →
["a"=>1,"b"=>2]
arsort($array) Sorts by value (descending).
krsort($array) Sorts by key (descending).
🔗 6. Combining and Splitting Arrays
Function Description Example
[1,2] + [3,4] →
array_merge($arr1, $arr2) Merges arrays. [1,2,3,4]
array_combine($keys, $values)
Combines two arrays into an ["a","b"], [1,2] →
associative array. ["a"=>1,"b"=>2]
array_slice($array, $offset,
$length) Extracts a slice of an array. [1,2,3,4] → [2,3]
array_splice($array, $offset, Removes or replaces
$length) elements.
🎯 7. Searching in Arrays
Function Description Example
in_array($needle, $array) Checks if value exists.
array_search($needle, $array) Returns key of a value.
array_key_exists($key, $array) Checks if key exists.
🧰 8. Array Filtering, Mapping, and Reducing
Function Description Example
array_map($callback, $array)
Applies a function to array_map('strtoupper',
each element. ['a','b']) → ['A','B']
array_filter($array, Filters elements
$callback) Keeps only elements that pass a test.
using a callback.
array_reduce($array, Reduces array to a Sum of all numbers, etc.
Function Description Example
$callback, $initial) single value.
🧮 9. Set Operations
Function Description Example
[1,2,2,3] →
array_unique($array) Removes duplicate values. [1,2,3]
array_diff($arr1, $arr2)
Returns difference (values in arr1 not in
arr2).
array_intersect($arr1,
$arr2) Returns common values.
📜 10. Other Useful Functions
Function Description
compact() Creates an array from variables and their values.
extract() Imports variables from an array into the current symbol table.
shuffle() Randomizes the order of array elements.
array_reverse() Reverses array order.
array_sum() Returns the sum of all elements.
array_product() Returns the product of all elements.
✅ Example
<?php
$numbers = [1, 2, 3, 4, 5];
// Filtering even numbers
$even = array_filter($numbers, fn($n) => $n % 2 == 0);
// Mapping (square numbers)
$squares = array_map(fn($n) => $n * $n, $numbers);
// Reducing (sum)
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
print_r($even);
print_r($squares);
echo "Sum: $sum";
?>
. Explain data and time function in PHP
A. Getting the Current Date and Time
Function Description Example
date($format, H:i:s") → 2025-10-30
$timestamp) Formats a local date/time. date("Y-m-d
15:45:22
Returns current Unix
time() time() → 1735597522
timestamp.
gmdate($format, Formats a GMT/UTC gmdate("Y-m-d H:i:s")
$timestamp) date/time.
🧠 Example:
echo date("Y-m-d H:i:s"); // Outputs: 2025-10-30 15:30:00
echo time(); // Outputs: 1735596000 (timestamp)
B. Converting Between Timestamps and Dates
Function Description Example
strtotime($time, $now)
Converts a string into a strtotime("next Monday")
timestamp.
mktime($hour, $min, $sec, $mon, Returns timestamp for a mktime(0, 0, 0, 10, 30,
$day, $year) given date. 2025)
getdate($timestamp)
Returns an array with
date/time info.
date_create($time, $timezone)
Creates a DateTime date_create("2025-10-
object. 30")
🧠 Example:
$timestamp = strtotime("2025-12-25");
echo date("l, d-M-Y", $timestamp); // Outputs: Thursday, 25-Dec-2025
🧭 C. Formatting Dates
The date() function uses format characters to define output format.
Format Character Meaning Example
d Day (two digits) 01–31
m Month (two digits) 01–12
Y Year (four digits) 2025
y Year (two digits) 25
H Hour (24-hour format) 00–23
h Hour (12-hour format) 01–12
i Minutes 00–59
Format Character Meaning Example
s Seconds 00–59
A AM/PM AM or PM
l Day name Monday
D Short day name Mon
F Full month name October
🧠 Example:
echo date("l, F j, Y, g:i A");
// Output: Thursday, October 30, 2025, 3:45 PM
🌍 D. Working with Time Zones
Function Description Example
date_default_timezone_get() Returns current timezone.
date_default_timezone_set($timezone) Sets default timezone.
timezone_identifiers_list() Returns all available time zones.
🧠 Example:
date_default_timezone_set("Asia/Kolkata");
echo date("Y-m-d H:i:s"); // Time in India
🧰 E. Using DateTime Class (Object-Oriented Way)
PHP’s DateTime class provides more flexibility for date manipulation.
Method Description Example
new DateTime($time) Creates DateTime object. $dt = new DateTime("2025-10-30");
$dt->format($format) Formats the date. $dt->format("Y-m-d")
$dt-
>modify($modifier) Modifies the date. $dt->modify("+1 week");
$dt->add(new
$dt->add($interval) Adds a DateInterval. DateInterval("P10D"));
$dt->sub($interval) Subtracts a DateInterval.
$dt->diff($otherDate)
Finds difference between
dates.
🧠 Example:
$date1 = new DateTime("2025-10-30");
$date2 = new DateTime("2025-12-25");
$interval = $date1->diff($date2);
echo $interval->days . " days difference."; // Outputs: 56 days difference.
🧮 F. Miscellaneous Functions
Function Description Example
checkdate($month, $day, checkdate(2, 29, 2025)
$year) Checks if a date is valid. → false
gettimeofday()
Returns current time info as an
array.
microtime($as_float)
Returns current Unix timestamp
with microseconds.
date_sunrise() / Returns sunrise/sunset time for a
date_sunset() location.
✅ Example Program:
<?php
date_default_timezone_set("Asia/Kolkata");
echo "Current Date & Time: " . date("Y-m-d H:i:s") . "<br>";
$future = strtotime("+10 days");
echo "After 10 days: " . date("Y-m-d", $future) . "<br>";
$date1 = new DateTime("2025-10-30");
$date2 = new DateTime("2025-12-25");
$interval = $date1->diff($date2);
echo "Days remaining until Christmas: " . $interval->days . " days<br>";
if (checkdate(2, 29, 2025))
echo "Valid date";
else
echo "Invalid date";
?>
Output:
Current Date & Time: 2025-10-30 15:45:00
After 10 days: 2025-11-09
Days remaining until Christmas: 56 days
Invalid date
Would you like me to include a quick reference table of the most used date() format
characters (like Y-m-d H:i:s → 2025-10-30 15:45:00)? It’s handy for memorizing formats.
What is a Transaction?
A transaction is a set of database operations that are treated as a single unit of work.
It ensures data integrity — meaning either all operations are completed successfully, or none of
them are applied.
For example:
If you are transferring money from one bank account to another, you want to subtract from one
account and add to the other.
If one operation fails, both should be rolled back — not half-done.
🔒 Transaction Properties (ACID)
Transactions follow the ACID properties:
Property Meaning
A — Atomicity All operations succeed or none do.
C — Consistency The database remains in a valid state.
I — Isolation Transactions are executed independently.
D — Durability Once committed, data is permanently saved.
How Transactions Work in PHP
Transactions are not handled directly by PHP itself —
they are managed by the database (like MySQL, PostgreSQL, etc.).
PHP interacts with them through extensions such as:
MySQLi (MySQL Improved Extension)
PDO (PHP Data Objects)
🧩 1. Transactions using MySQLi
✅ Example:
<?php
// Connect to database
$conn = new mysqli("localhost", "root", "", "bankdb");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Turn off auto-commit mode
$conn->autocommit(FALSE);
try {
// Withdraw from Account A
$conn->query("UPDATE accounts SET balance = balance - 500 WHERE id = 1");
// Deposit to Account B
$conn->query("UPDATE accounts SET balance = balance + 500 WHERE id = 2");
// Check for errors
if ($conn->error) {
throw new Exception($conn->error);
}
// Commit the transaction
$conn->commit();
echo "Transaction Successful!";
} catch (Exception $e) {
// Rollback if something failed
$conn->rollback();
echo "Transaction Failed: " . $e->getMessage();
}
// Close connection
$conn->close();
?>
🔍 Explanation:
autocommit(FALSE) disables automatic saving.
commit() saves all the changes if successful.
rollback() undoes all operations if an error occurs.
🧮 2. Transactions using PDO
PDO provides a simpler, object-oriented interface.
✅ Example:
<?php
try {
// Create connection
$pdo = new PDO("mysql:host=localhost;dbname=bankdb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Begin transaction
$pdo->beginTransaction();
// Execute queries
$pdo->exec("UPDATE accounts SET balance = balance - 500 WHERE id = 1");
$pdo->exec("UPDATE accounts SET balance = balance + 500 WHERE id = 2");
// Commit changes
$pdo->commit();
echo "Transaction completed successfully!";
} catch (Exception $e) {
// Rollback on error
$pdo->rollBack();
echo "Transaction failed: " . $e->getMessage();
}
?>
🧠 3. Notes and Best Practices
Transactions only work with tables that support them — e.g., InnoDB in MySQL (not
MyISAM).
Always use try...catch blocks to handle exceptions.
Disable autocommit before beginning a transaction.
Use transactions for critical operations (banking, inventory updates, etc.).
Rollback ensures database consistency in case of errors.
✅ Summary Table
Function / Method Description
$conn->autocommit(false) Turns off auto-commit mode
$conn->commit() Commits (saves) all changes
$conn->rollback() Reverts all changes
$pdo->beginTransaction() Begins a transaction
$pdo->commit() Commits the transaction
$pdo->rollBack() Rolls back the transaction
💬 Example Output:
Transaction Successful!
Or, if something fails:
Transaction Failed: Error message
Would you like me to show an example where one query fails (so you can see rollback in
action)?
It helps visualize how transactions prevent partial updates.
Get smarter responses, upload files and image
What is CRUD?
CRUD stands for:
C → Create
R → Read
U → Update
D → Delete
These are the four basic operations performed on database records in most applications