Data Analytics
27.4K subscribers
1.18K photos
24 videos
33 files
997 links
Dive into the world of Data Analytics – uncover insights, explore trends, and master data-driven decision making.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Topic: PHP Basics – Part 3 of 10: Control Structures (if, else, elseif, switch, loops)

---

1. Conditional Statements in PHP

PHP allows decision-making in your code through control structures like if, else, elseif, and switch.

---

2. `if`, `else`, and `elseif` Statements

<?php
$score = 85;

if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}
?>


• The condition inside if() must return true or false.

• You can chain multiple conditions using elseif.

---

3. `switch` Statement

• Good for checking a variable against multiple possible values.

<?php
$day = "Tuesday";

switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Weekend is near!";
break;
case "Sunday":
echo "Rest day!";
break;
default:
echo "Just another day.";
}
?>


• Each case must end with a break to avoid fall-through.

---

4. Loops in PHP

Loops allow repeating code multiple times.

---

5. `while` Loop

<?php
$i = 0;
while ($i < 5) {
echo "Number: $i<br>";
$i++;
}
?>


• Repeats while the condition is true.

---

6. `do...while` Loop

<?php
$i = 0;
do {
echo "Count: $i<br>";
$i++;
} while ($i < 3);
?>


• Executes at least once even if the condition is false initially.

---

7. `for` Loop

<?php
for ($i = 1; $i <= 5; $i++) {
echo "Line $i<br>";
}
?>


• Most commonly used loop with initializer, condition, and increment.

---

8. `foreach` Loop

• Used to iterate over arrays.

<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "Color: $color<br>";
}
?>


• Also works with key-value pairs:

<?php
$person = array("name" => "Ali", "age" => 28);
foreach ($person as $key => $value) {
echo "$key: $value<br>";
}
?>


---

9. Control Keywords

break – Exit a loop or switch.
continue – Skip current iteration and go to the next.

for ($i = 1; $i <= 5; $i++) {
if ($i == 3) continue;
echo "$i<br>";
}


---

10. Summary

• Conditional logic (if, else, switch) helps make decisions.

• Loops (for, while, foreach) help automate repetitive tasks.

• Control flow is critical for building dynamic applications.

---

Exercise

• Write a PHP script that prints numbers 1 to 20, but skips multiples of 3 using continue, and stops completely if the number is 17 using break.

---

#PHP #ControlStructures #Loops #PHPTutorial #BackendDevelopment

https://t.iss.one/Ebooks2023
1🔥1
Topic: PHP Basics – Part 4 of 10: Arrays in PHP (Indexed, Associative, Multidimensional)

---

1. What is an Array in PHP?

• An array is a special variable that can hold multiple values at once.

• In PHP, arrays can be indexed, associative, or multidimensional.

---

2. Indexed Arrays

• Stores values with a numeric index (starting from 0).

$fruits = array("apple", "banana", "cherry");
echo $fruits[1]; // Output: banana


• Add elements:

$fruits[] = "grape"; // Adds to the end of the array


• Count elements:

echo count($fruits); // Output: 4


• Loop through indexed array:

foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}


---

3. Associative Arrays

• Uses named keys instead of numeric indexes.

$person = array(
"name" => "Ali",
"age" => 30,
"city" => "Istanbul"
);
echo $person["name"]; // Output: Ali


• Loop through associative array:

foreach ($person as $key => $value) {
echo "$key: $value<br>";
}


---

4. Multidimensional Arrays

• Arrays containing one or more arrays.

$students = array(
array("Ali", 90, 85),
array("Sara", 95, 88),
array("Omar", 78, 82)
);

echo $students[0][0]; // Output: Ali
echo $students[1][2]; // Output: 88


• Loop through multidimensional array:

for ($i = 0; $i < count($students); $i++) {
for ($j = 0; $j < count($students[$i]); $j++) {
echo $students[$i][$j] . " ";
}
echo "<br>";
}


---

5. Array Functions You Should Know

count() – Number of elements
array_push() – Add to end
array_pop() – Remove last element
array_merge() – Merge arrays
in_array() – Check if value exists
array_keys() – Get all keys
sort(), rsort() – Sort indexed array
asort(), ksort() – Sort associative array by value/key

$colors = array("red", "blue", "green");
sort($colors);
print_r($colors);


---

6. Summary

• Arrays are powerful tools for storing multiple values.

• Indexed arrays use numeric keys; associative arrays use named keys.

• PHP supports nested arrays for more complex structures.

---

Exercise

• Create a multidimensional array of 3 students with their names and 2 grades.

• Print the average grade of each student using a nested loop.

---

#PHP #Arrays #Multidimensional #PHPTutorial #BackendDevelopment

https://t.iss.one/Ebooks2023
3
Topic: PHP Basics – Part 8 of 10: Working with Files and Directories

---

1. Introduction to File Handling in PHP

• PHP allows you to create, read, write, append, and delete files on the server.

• You can also manage directories, check if a file exists, and more.

---

2. Opening a File

Use the fopen() function:

$handle = fopen("example.txt", "r");


"r" means read-only. Other modes include:

| Mode | Description |
| ------ | -------------------------------- |
| "r" | Read-only |
| "w" | Write-only (truncates file) |
| "a" | Append |
| "x" | Create & write (fails if exists) |
| "r+" | Read & write |

---

3. Reading from a File

$handle = fopen("example.txt", "r");
$content = fread($handle, filesize("example.txt"));
fclose($handle);

echo $content;


fread() reads the entire file based on its size.

• Always use fclose() to release system resources.

---

4. Writing to a File

$handle = fopen("newfile.txt", "w");
fwrite($handle, "Hello from PHP file writing!");
fclose($handle);


• If the file doesn't exist, it will be created.

• If it exists, it will be overwritten.

---

5. Appending to a File

$handle = fopen("log.txt", "a");
fwrite($handle, "New log entry\n");
fclose($handle);


"a" keeps existing content and adds to the end.

---

6. Reading Line by Line

$handle = fopen("example.txt", "r");
while (!feof($handle)) {
$line = fgets($handle);
echo $line . "<br>";
}
fclose($handle);


feof() checks for end of file.

fgets() reads a single line.

---

7. Checking If File Exists

if (file_exists("example.txt")) {
echo "File found!";
} else {
echo "File not found!";
}


---

8. Deleting a File

if (file_exists("delete_me.txt")) {
unlink("delete_me.txt");
echo "File deleted.";
}


---

9. Working with Directories

Create a directory:

mkdir("myfolder");


Check if a directory exists:

if (is_dir("myfolder")) {
echo "Directory exists!";
}


Delete a directory:

rmdir("myfolder"); // Only works if empty


---

10. Scanning a Directory

$files = scandir("myfolder");
print_r($files);


• Returns an array of file and directory names.

---

11. Uploading Files

This is a common use case when working with files in PHP.

HTML Form:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedFile">
<input type="submit" value="Upload">
</form>


upload.php:

if ($_FILES["uploadedFile"]["error"] === 0) {
$target = "uploads/" . basename($_FILES["uploadedFile"]["name"]);
move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target);
echo "Upload successful!";
}


---

12. Summary

• PHP provides powerful tools for file and directory operations.

• You can manage content, upload files, read/write dynamically, and handle directories with ease.

---

Exercise

• Create a PHP script that:

* Checks if a file named data.txt exists
* If it does, reads and prints its contents
* If not, creates the file and writes a welcome message

---

#PHP #FileHandling #Directories #PHPTutorial #BackendDevelopment

https://t.iss.one/Ebooks2023
2
Topic: PHP Basics – Part 9 of 10: Sessions, Cookies, and State Management

---

1. Why Use Sessions and Cookies?

• HTTP is stateless – every request is independent.
• To remember users or store temporary data (like login), we use sessions and cookies.

---

### 2. Sessions in PHP

• Sessions store data on the server.

---

Starting a Session

<?php
session_start(); // Always at the top
$_SESSION["username"] = "Ali";
?>


• This creates a unique session ID per user and stores data on the server.

---

Accessing Session Data

<?php
session_start();
echo $_SESSION["username"]; // Output: Ali
?>


---

Destroying a Session

<?php
session_start();
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
?>


---

Use Cases for Sessions

• Login authentication
• Shopping carts
• Flash messages (e.g., "You’ve logged out")

---

### 3. Cookies in PHP

• Cookies store data on the client’s browser.

---

Setting a Cookie

setcookie("user", "Ali", time() + (86400 * 7)); // 7 days


• Syntax: setcookie(name, value, expiration, path, domain, secure, httponly)

---

Accessing Cookie Values

echo $_COOKIE["user"];


---

Deleting a Cookie

setcookie("user", "", time() - 3600); // Expire it in the past


---

Session vs Cookie

| Feature | Session | Cookie |
| ---------- | -------------------------------- | ------------ |
| Storage | Server-side | Client-side |
| Size Limit | Large (server) | \~4KB |
| Expiry | On browser close or set manually | Manually set |
| Security | More secure | Less secure |

---

### 4. Best Practices

• Always use session_start() before outputting anything.

• Use secure flags (secure, httponly) when setting cookies.

setcookie("auth", "token", time()+3600, "/", "", true, true);


---

5. Session Timeout Handling

session_start();
$timeout = 600; // 10 minutes

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $timeout)) {
session_unset();
session_destroy();
echo "Session expired.";
}
$_SESSION['LAST_ACTIVITY'] = time();


---

6. Flash Messages with Sessions

// Set message
$_SESSION["message"] = "Login successful!";

// Display then clear
if (isset($_SESSION["message"])) {
echo $_SESSION["message"];
unset($_SESSION["message"]);
}


---

### 7. Summary

Sessions are best for storing temporary and secure server-side user data.

Cookies are useful for small, client-side persistent data.

• Use both wisely to build secure and dynamic web applications.

---

Exercise

• Create a login form that stores the username in a session.
• Set a welcome cookie that lasts 1 day after login.
• Display both the session and cookie values after login.

---

#PHP #Sessions #Cookies #Authentication #PHPTutorial #BackendDevelopment

https://t.iss.one/Ebooks2023