├── .gitignore ├── images └── oop1.png ├── module1 ├── 10_conditionals.php ├── 11_if_else.php ├── 12_ternary_operator.php ├── 13_nested_ternary.php ├── 14_switch.php ├── 15_coding_challenge.js ├── 16_server.js ├── 1_agenda.js ├── 2_intro_php.js ├── 3_variables.php ├── 4_constants.php ├── 5_comments.php ├── 6_printing.php ├── 7_arithmetic_operation.php ├── 8_number_system.php ├── 9_printf.php ├── index.php ├── main.php └── project │ └── calculator │ ├── index.php │ └── styles.css ├── module2 ├── 1_agenda.js ├── 2_loop.js ├── 3_forloop.js ├── 4_break_continue.js ├── 5_fibonacci.js ├── 6_function.js ├── 7_function_advance.js ├── 8_scope.js └── 9_multiplication_table.js ├── module3 ├── 1_array_basic.php ├── 2_associative_multidimensional_array.php ├── 3_array_function.php ├── 4_handle_string.php ├── main.php ├── project │ └── tic_tac_toe.php ├── string.php └── topic_module3.php └── topics.js /.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/understand_php/980f5df580ae18928757b620348bf1ea0f895b76/.gitignore -------------------------------------------------------------------------------- /images/oop1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/faisal2410/understand_php/980f5df580ae18928757b620348bf1ea0f895b76/images/oop1.png -------------------------------------------------------------------------------- /module1/10_conditionals.php: -------------------------------------------------------------------------------- 1 | 5 | 6 | 14 | 15 | 16 | 17 | 18 | 28 | 29 | 57 | 58 | 68 | 69 | 78 | 79 | 83 | 84 | 93 | 94 | 95 | 97 | 98 | 106 | 110 | 111 | 112 | 113 | 114 | 115 | 117 | 118 | 119 | 128 | 129 | 130 | 132 | 133 | 141 | 142 | 145 | 146 | 154 | 155 | 156 | 158 | 159 | 171 | 172 | 173 | 175 | 176 | 186 | 187 | 188 | 190 | 191 | 199 | 200 | 202 | 203 | 211 | 212 | 213 | 214 | 216 | 217 | 230 | 231 | 232 | 234 | 235 | 243 | 244 | 245 | 247 | 248 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | -------------------------------------------------------------------------------- /module1/11_if_else.php: -------------------------------------------------------------------------------- 1 | 5 | 6 | 13 | 14 | 15 | 16 | 17 | 28 | 29 | 30 | 31 | 32 | 34 | 35 | 36 | 37 | 48 | 49 | 50 | 51 | 53 | 54 | 63 | 64 | 65 | 66 | 67 | = 13 && $age < 20) { 74 | echo "You are a teenager."; 75 | } else { 76 | echo "You are an adult."; 77 | } 78 | 79 | ?> 80 | 81 | 82 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /module1/12_ternary_operator.php: -------------------------------------------------------------------------------- 1 | 5 | 6 | 14 | 15 | 23 | 24 | 30 | 31 | 32 | 33 | 34 | 38 | 39 | 43 | 44 | 45 | 46 | 47 | 51 | 52 | 53 | 55 | 62 | 63 | 64 | 65 | 66 | 68 | 69 | 70 | 71 | 75 | 76 | 78 | 79 | 83 | 84 | 85 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /module1/13_nested_ternary.php: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 12 | 13 | 19 | 20 | 25 | 26 | 30 | 33 | 34 | 40 | 41 | 42 | 47 | 48 | 55 | 56 | 57 | 66 | 67 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /module1/14_switch.php: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 21 | 22 | 52 | 53 | 63 | 64 | 65 | 66 | 70 | 71 | 80 | 81 | 85 | 86 | 97 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /module1/15_coding_challenge.js: -------------------------------------------------------------------------------- 1 | // Here are 19 coding challenges based on the concepts of PHP you provided: 2 | 3 | // 1. Variables 4 | 5 | // Variable Declaration and Initialization: Create two variables - one storing your name (string) and the other storing your age (int). Print them. 6 | // Global vs. Local: Declare a global variable and a function that tries to print this global variable without using the global keyword. Then try with the global keyword. 7 | // 2. Constants 8 | 9 | // Constant Creation: Define a constant that stores the value of Pi (3.14159) and print it. 10 | // Variables vs Constants: Try to change the value of the constant defined in the previous challenge. Observe the result. 11 | // 3. Comments 12 | 13 | // Commenting Code: Write a function with both single-line and multi-line comments explaining what the function does. 14 | // 4. Printing Output 15 | 16 | // Echo vs Print: Use both echo and print statements to display your favorite quote. 17 | // String Concatenation: Concatenate two strings - "Hello" and "World", and display the result. 18 | // Escape Characters: Print a string that includes a new line and a tab using escape characters. 19 | // 5. Arithmetic Operations 20 | 21 | // Basic Calculations: Accept two numbers from a user and display their sum, difference, product, and quotient. 22 | // Modulus Operator: Input a number and display if it's even or odd using the modulus operator. 23 | // 6. Number Systems 24 | 25 | // Number Conversion: Convert a decimal number 255 to binary, octal, and hexadecimal. 26 | // 7. Printf Function 27 | 28 | // Formatted Output: Use the printf() function to print a float number with 2 decimal points. 29 | // 8. Conditional Statements 30 | 31 | // Simple Condition: Ask the user for their age and print whether they are a minor or an adult using the if statement. 32 | // Logical Operators: Write a program that checks if a number is both even and greater than 10. 33 | // 9. If-Else Statements 34 | 35 | // Temperature Feedback: Input the current temperature and provide feedback. If it's below 20°C, say it's cold; between 20°C and 30°C, say it's pleasant; above 30°C, say it's hot. 36 | // 10. Ternary Operator 37 | 38 | // Simple Ternary: Convert the temperature feedback logic from challenge 15 into a single line using the ternary operator. 39 | // 11. Nested Ternary Operators 40 | 41 | // Advanced Ternary: Implement a simple calculator that takes 3 inputs - two numbers and an operation (+, -, *, /) and displays the result using nested ternary operators. 42 | // 12. Switch Case Statements 43 | 44 | // Days of the Week: Accept a number between 1 and 7 and print the corresponding day of the week using a switch-case. 45 | // Strict vs Loose Comparison: Using a switch case, compare a string '10' with an integer 10 using both loose and strict comparisons. 46 | // Default Case: Enhance the "Days of the Week" challenge to include a default case which handles numbers outside the range of 1-7. 47 | // These challenges should provide a comprehensive practice over the mentioned PHP concepts. Happy coding! 48 | 49 | 50 | 51 | // 13. Dynamic Variable Names 52 | 53 | // Challenge: Create a string variable with a value of 'age'. Then, using this string, dynamically create another variable named 'age' that stores the value 25. Print the value of this new variable. 54 | // 14. Constants with Arrays 55 | 56 | // Challenge: Define a constant that holds an array of your favorite colors. Display the third color in the list. 57 | // 15. Advanced String Formatting with Printf 58 | 59 | // Challenge: Use the printf() function to display a formatted string containing a person's first name, last name, and age, ensuring that the age is right-aligned and occupies 3 spaces. 60 | // 16. Nested If-Else for Grades 61 | 62 | // Challenge: Accept a student's score (0 to 100) and provide a grade: 63 | // A (>=90) 64 | // B (>=75 and <90) 65 | // C (>=50 and <75) 66 | // D (<50) 67 | // 17. Ternary for Login Feedback 68 | 69 | // Challenge: Simulate a login mechanism. If a user's username is 'admin' and password is 'password123', display 'Welcome Admin'. For incorrect details, use a ternary operator to display 'Invalid Password' if the username is correct, otherwise display 'Invalid Username'. 70 | // 18. Complex Nested Ternary 71 | 72 | // Challenge: Given three integers, use a nested ternary operator to determine and display the largest one. 73 | // 19. Enhanced Switch Case with Functions 74 | 75 | // Challenge: Create a calculator function that accepts two numbers and an operation (add, subtract, multiply, divide) as arguments. Use a switch-case inside the function to perform the operation and return the result. The function should handle invalid operations gracefully. 76 | // I hope these challenges further enhance your understanding and mastery of PHP. 77 | 78 | 79 | 80 | // Solutions : 81 | 82 | // 1. Variables 83 | 84 | // Variable Declaration and Initialization 85 | // $name = "John"; 86 | // $age = 30; 87 | // echo "Name: $name, Age: $age\n"; 88 | 89 | // // Global vs. Local 90 | // $globalVar = "I am a global variable"; 91 | 92 | // function displayVar() { 93 | // // This won't work as we are not using the 'global' keyword 94 | // // echo $globalVar; 95 | 96 | // global $globalVar; 97 | // echo $globalVar; 98 | // } 99 | 100 | // displayVar(); 101 | 102 | // // 2. Constants 103 | 104 | // // Constant Creation 105 | // define("PI", 3.14159); 106 | // echo PI . "\n"; 107 | 108 | // // Variables vs Constants 109 | // // This will result in an error since constants can't be redefined 110 | // // PI = 3.14; 111 | 112 | // // 3. Comments 113 | 114 | // // Commenting Code 115 | // function add($a, $b) { 116 | // // This function adds two numbers 117 | // /* 118 | // Multi-line comment: 119 | // It takes two parameters: 120 | // a - First number 121 | // b - Second number 122 | // */ 123 | // return $a + $b; 124 | // } 125 | 126 | // // 4. Printing Output 127 | 128 | // // Echo vs Print 129 | // echo "Life is what happens when you're busy making other plans.\n"; 130 | // print "Life is what happens when you're busy making other plans.\n"; 131 | 132 | // // String Concatenation 133 | // echo "Hello " . "World" . "\n"; 134 | 135 | // // Escape Characters 136 | // echo "This is a new line.\n\tAnd this is a tab.\n"; 137 | 138 | // // 5. Arithmetic Operations 139 | 140 | // // Basic Calculations 141 | // $number1 = 10; // Sample input 142 | // $number2 = 20; // Sample input 143 | // echo "Sum: " . ($number1 + $number2) . "\n"; 144 | // echo "Difference: " . ($number1 - $number2) . "\n"; 145 | // echo "Product: " . ($number1 * $number2) . "\n"; 146 | // echo "Quotient: " . ($number1 / $number2) . "\n"; 147 | 148 | // // Modulus Operator 149 | // $number = 5; // Sample input 150 | // echo ($number % 2 == 0) ? "Even" : "Odd"; 151 | 152 | // // 6. Number Systems 153 | 154 | // // Number Conversion 155 | // $decimal = 255; 156 | // echo "Binary: " . decbin($decimal) . "\n"; 157 | // echo "Octal: " . decoct($decimal) . "\n"; 158 | // echo "Hexadecimal: " . dechex($decimal) . "\n"; 159 | 160 | // // 7. Printf Function 161 | 162 | // // Formatted Output 163 | // $floatNumber = 10.456789; // Sample input 164 | // printf("%.2f\n", $floatNumber); 165 | 166 | // // 8. Conditional Statements 167 | 168 | // // Simple Condition 169 | // $userAge = 18; // Sample input 170 | // if ($userAge < 18) { 171 | // echo "You are a minor.\n"; 172 | // } else { 173 | // echo "You are an adult.\n"; 174 | // } 175 | 176 | // // Logical Operators 177 | // $number = 15; // Sample input 178 | // if ($number % 2 == 0 && $number > 10) { 179 | // echo "The number is even and greater than 10.\n"; 180 | // } else { 181 | // echo "The number does not meet the criteria.\n"; 182 | // } 183 | 184 | // // 9. If-Else Statements 185 | 186 | // // Temperature Feedback 187 | // $temperature = 25; // Sample input 188 | // if ($temperature < 20) { 189 | // echo "It's cold.\n"; 190 | // } elseif ($temperature >= 20 && $temperature <= 30) { 191 | // echo "It's pleasant.\n"; 192 | // } else { 193 | // echo "It's hot.\n"; 194 | // } 195 | 196 | // // 10. Ternary Operator 197 | 198 | // // Simple Ternary 199 | // echo ($temperature < 20) ? "It's cold." : (($temperature <= 30) ? "It's pleasant." : "It's hot."); 200 | 201 | 202 | 203 | 204 | 205 | // 11. Nested Ternary Operators 206 | 207 | // $num1 = 10; 208 | // $num2 = 20; 209 | // $operation = '+'; // Sample operation 210 | 211 | // $result = ($operation == '+') ? $num1 + $num2 : 212 | // (($operation == '-') ? $num1 - $num2 : 213 | // (($operation == '*') ? $num1 * $num2 : 214 | // (($operation == '/') ? $num1 / $num2 : "Invalid Operation"))); 215 | 216 | // echo "Result: $result\n"; 217 | 218 | // // 12. Switch Case Statements 219 | 220 | // // Days of the Week 221 | // $dayNumber = 5; // Sample number 222 | 223 | // switch($dayNumber) { 224 | // case 1: 225 | // echo "Monday\n"; 226 | // break; 227 | // case 2: 228 | // echo "Tuesday\n"; 229 | // break; 230 | // case 3: 231 | // echo "Wednesday\n"; 232 | // break; 233 | // case 4: 234 | // echo "Thursday\n"; 235 | // break; 236 | // case 5: 237 | // echo "Friday\n"; 238 | // break; 239 | // case 6: 240 | // echo "Saturday\n"; 241 | // break; 242 | // case 7: 243 | // echo "Sunday\n"; 244 | // break; 245 | // default: 246 | // echo "Invalid number\n"; 247 | // } 248 | 249 | // // Strict vs Loose Comparison 250 | // $value = '10'; 251 | 252 | // switch(true) { 253 | // case ($value == 10): 254 | // echo "Loose match\n"; 255 | // break; 256 | // case ($value === 10): 257 | // echo "Strict match\n"; 258 | // break; 259 | // default: 260 | // echo "No match\n"; 261 | // } 262 | 263 | // // 13. Dynamic Variable Names 264 | 265 | // $stringVariable = 'age'; 266 | // $$stringVariable = 25; // Creates a variable named $age 267 | // echo $age . "\n"; 268 | 269 | // // 14. Constants with Arrays 270 | 271 | // define("COLORS", ["Red", "Blue", "Green", "Yellow"]); 272 | // echo COLORS[2] . "\n"; 273 | 274 | // // 15. Advanced String Formatting with Printf 275 | 276 | // $firstName = "John"; 277 | // $lastName = "Doe"; 278 | // $age = 27; 279 | // printf("Name: %s %s, Age: %3d\n", $firstName, $lastName, $age); 280 | 281 | // // 16. Nested If-Else for Grades 282 | 283 | // $score = 85; 284 | 285 | // if ($score >= 90) { 286 | // echo "Grade: A\n"; 287 | // } elseif ($score >= 75) { 288 | // echo "Grade: B\n"; 289 | // } elseif ($score >= 50) { 290 | // echo "Grade: C\n"; 291 | // } else { 292 | // echo "Grade: D\n"; 293 | // } 294 | 295 | // // 17. Ternary for Login Feedback 296 | 297 | // $username = "admin"; 298 | // $password = "password123"; 299 | 300 | // $message = ($username == "admin") ? 301 | // (($password == "password123") ? "Welcome Admin" : "Invalid Password") 302 | // : "Invalid Username"; 303 | // echo $message . "\n"; 304 | 305 | // // 18. Complex Nested Ternary 306 | 307 | // $a = 5; 308 | // $b = 15; 309 | // $c = 10; 310 | 311 | // $largest = ($a > $b) ? (($a > $c) ? $a : $c) : (($b > $c) ? $b : $c); 312 | // echo "Largest: $largest\n"; 313 | 314 | // // 19. Enhanced Switch Case with Functions 315 | 316 | // function calculator($num1, $num2, $operation) { 317 | // switch($operation) { 318 | // case "add": 319 | // return $num1 + $num2; 320 | // case "subtract": 321 | // return $num1 - $num2; 322 | // case "multiply": 323 | // return $num1 * $num2; 324 | // case "divide": 325 | // if($num2 == 0) { 326 | // return "Division by zero is not allowed."; 327 | // } 328 | // return $num1 / $num2; 329 | // default: 330 | // return "Invalid operation."; 331 | // } 332 | // } 333 | 334 | // echo calculator(10, 5, "add"); 335 | -------------------------------------------------------------------------------- /module1/16_server.js: -------------------------------------------------------------------------------- 1 | // Understanding $_SERVER 2 | // In PHP, $_SERVER is a superglobal variable, which means that it is available in all scopes throughout a script. It is an array that holds information about headers, paths, and script locations. The entries in this array are created by the web server and contain data related to the current script and the HTTP request. 3 | 4 | // Here's an example of using $_SERVER to get the user's IP address and the user agent string (which identifies the user's browser): 5 | 6 | 7 | // '; 9 | // echo 'User Agent: ' . $_SERVER['HTTP_USER_AGENT'] . '
'; 10 | // ?> 11 | 12 | 13 | // Understanding $_SERVER["REQUEST_METHOD"] 14 | // The $_SERVER["REQUEST_METHOD"] entry in the $_SERVER superglobal array allows you to determine the HTTP method used to access the page. Typically, this will be one of the methods like 'GET', 'POST', 'PUT', 'DELETE', etc. 15 | 16 | // In many cases, you will use this entry to check if a form has been submitted using the "POST" method, like this: 17 | 18 | 19 | // 25 | 26 | 27 | // Combining $_SERVER and $_SERVER["REQUEST_METHOD"] to Handle Form Submissions 28 | // Let's build upon the previous example to demonstrate how you might use $_SERVER["REQUEST_METHOD"] to handle form submissions in a real PHP script. Below, we have a simple HTML form and a PHP script that processes the form data if the request method is "POST": 29 | 30 | 31 | // 38 | 39 | // 40 | // 41 | // 42 | // Form Handling in PHP 43 | // 44 | // 45 | 46 | //
47 | // Name:

48 | // 49 | //
50 | 51 | // 52 | // 53 | 54 | // In the above script: 55 | 56 | // We use $_SERVER["REQUEST_METHOD"] to check if the form was submitted using the POST method. 57 | // If the form was submitted using the POST method, we use the $_POST superglobal to get the value of the name input field. 58 | // We then use htmlspecialchars() to sanitize the input and prevent XSS attacks before echoing a greeting to the user. 59 | // I hope this gives you a clear understanding! If you have any further questions or topics you'd like to explore, feel free to ask. 60 | 61 | 62 | // ✅Understanding $_POST 63 | // In PHP, $_POST is a superglobal array that is used to collect form data sent in an HTTP POST request. It allows you to access the data sent in the request body, which is often used to collect data from HTML forms. 64 | 65 | // Usage of $_POST 66 | // 1. Basic Usage 67 | // You can use $_POST to get the value of individual form fields using syntax like $_POST['fieldname']. Here's a basic example: 68 | 69 | 70 | // 76 | //
77 | // Name:

78 | // 79 | //
80 | // In this script: 81 | 82 | // The HTML form uses the POST method to send data to the server. 83 | // We use $_POST['name'] to get the value of the name input field when the form is submitted. 84 | // 2. Sanitizing Input 85 | // To protect your application from XSS (Cross-Site Scripting) attacks and other potential vulnerabilities, it's essential to sanitize user input before using it. You can use PHP's htmlspecialchars function to do this: 86 | 87 | 88 | // 94 | // 3. Checking if a Form Field is Set 95 | // Before you access a form field with $_POST, it's a good practice to check if the field is set using isset() to avoid PHP undefined index notices: 96 | 97 | 98 | // 108 | // 4. Working with Different Input Types 109 | // You can work with various input types, such as text, radio buttons, checkboxes, and others using $_POST. Here is an example with a radio button: 110 | 111 | 112 | // 118 | //
119 | // Male
120 | // Female

121 | // 122 | //
123 | // I hope this helps you understand how to use $_POST in PHP! If you have any further questions, feel free to ask. 124 | 125 | 126 | 127 | 128 | 129 | 130 | // 133 | 134 | // '; 136 | // echo 'User Agent: ' . $_SERVER['HTTP_USER_AGENT'] . '
'; 137 | // ?> 138 | 139 | 140 | -------------------------------------------------------------------------------- /module1/1_agenda.js: -------------------------------------------------------------------------------- 1 | // PHP Basics 2 | //👉 1. PHP Environment Setup 3 | // Installing a local server (XAMPP) 4 | // Setting up a code editor (Visual Studio Code) 5 | // 👉2. Variables 6 | // Introduction to variables and data types (int, float, string, bool) 7 | // Variable naming conventions and rules 8 | // Variable scope (local, global) 9 | // 👉3. Constants 10 | // Defining constants using define() 11 | // Naming conventions for constants 12 | // Difference between variables and constants 13 | // 👉4. Comments 14 | // Single-line comments 15 | // Multi-line comments 16 | // Comments for code documentation 17 | // 👉5. Printing Output 18 | // Using echo and print statements 19 | // Concatenating strings and variables 20 | // Formatting output using escape characters 21 | // 👉6. Arithmetic Operations 22 | // Addition, subtraction, multiplication, division 23 | // Modulus (remainder) operation 24 | // Operator precedence and associativity 25 | // 👉7. Number Systems 26 | // Binary, octal, decimal, hexadecimal 27 | // Converting between number systems 28 | // 👉8. Printf Function 29 | // Using printf() for formatted output 30 | // Specifiers for different data types (%d, %f, %s, %c) 31 | // Formatting options (width, precision) 32 | // 👉9. Conditional Statements 33 | // Introduction to if statements 34 | // Using comparison operators (==, !=, <, >, <=, >=) 35 | // Building conditions using logical operators (&&, ||, !) 36 | // 👉10. If-Else Statements 37 | // Adding an else block to handle alternate conditions 38 | // Nesting if-else statements for complex conditions 39 | // 👉11. Ternary Operator 40 | // Syntax and usage of the ternary operator (condition ? true : false) 41 | // Replacing simple if-else statements with ternary 42 | // 👉12. Nested Ternary Operators 43 | // Using multiple levels of ternary operators 44 | // Considerations for readability and maintainability 45 | // 👉13. Switch Case Statements 46 | // Syntax and purpose of switch-case statements 47 | // Handling different cases and using the default case 48 | // Comparison using strict (===) vs. loose (==) equality 49 | 50 | 51 | // 👉Teaching Approach: 52 | // Start with a brief introduction to PHP and its importance in web development. 53 | // Progress through the topics in a logical order, building on each concept. 54 | // Provide plenty of code examples and practical exercises for hands-on practice. 55 | // Encourage students to experiment with code variations to solidify their understanding. 56 | // Offer coding challenges that require combining multiple concepts. 57 | // Highlight best practices and coding standards as you teach each topic. 58 | // Include real-world examples to show how these concepts are used in actual PHP projects. 59 | // Make use of interactive tools, quizzes, and projects to keep students engaged. 60 | // Remember that practice is crucial in coding, so allocate plenty of time for coding exercises and projects. By following this curriculum, your students will have a solid foundation in PHP programming and be well-prepared to tackle more advanced topics in the future. 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /module1/2_intro_php.js: -------------------------------------------------------------------------------- 1 | // 👉Introduction to PHP and Its Importance in Web Development 2 | // PHP (Hypertext Preprocessor) is a widely-used open-source scripting language specifically designed for web development. It's embedded within HTML code and executed on the server-side, generating dynamic web content that is then sent to the user's browser. 3 | 4 | //👉 Importance in Web Development: 5 | 6 | // Server-Side Scripting: PHP is primarily used for server-side scripting, which means it runs on the web server before sending the output to the client's browser. This enables the creation of dynamic and interactive web pages. 7 | 8 | // Dynamic Web Content: Unlike static HTML, PHP allows developers to create websites that respond to user interactions, database queries, and various conditions. This dynamic nature enhances user experience and interactivity. 9 | 10 | // Database Integration: PHP seamlessly integrates with databases like MySQL, allowing web applications to store, retrieve, and manipulate data. This is crucial for creating content-rich websites and web applications. 11 | 12 | // Efficiency: PHP is highly efficient for web development tasks due to its lightweight nature and optimized execution. It's designed to handle the demands of web traffic without excessive resource consumption. 13 | 14 | // Versatility: PHP can be used for various web-related tasks, including form handling, file manipulation, authentication, sessions, and more. It's well-suited for creating e-commerce sites, blogs, content management systems, and social networks. 15 | 16 | // Open Source and Active Community: Being open-source, PHP has a vast community of developers who contribute to its continuous improvement. This results in frequent updates, bug fixes, and new features, ensuring the language remains relevant and secure. 17 | 18 | // Widely Used: PHP is one of the most popular server-side scripting languages, and as a result, a large number of websites and web applications, including some of the most prominent ones, are built using PHP. 19 | 20 | // Integration with HTML: PHP code is embedded within HTML, making it easy to mix dynamic content with static elements. This seamless integration simplifies the development process. 21 | 22 | // In summary, PHP is a versatile and powerful scripting language that plays a pivotal role in web development. It empowers developers to create dynamic, interactive, and data-driven websites, enhancing user experiences and enabling the creation of complex web applications. As you delve into learning PHP, you'll unlock the ability to create websites that go beyond static content and engage users with dynamic features. 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /module1/3_variables.php: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 19 | 20 | 21 | 23 | 24 | 25 | 26 | 40 | 41 | 42 | 43 | 46 | 47 | 48 | 49 | 64 | 65 | 66 | 67 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 93 | 94 | 95 | 96 | 97 | 106 | 107 | 108 | 109 | 110 | 118 | 119 | 120 | 121 | 122 | 133 | 134 | 135 | 136 | 137 | 146 | 147 | 148 | 149 | 150 | 159 | 160 | 161 | 162 | 169 | 170 | 171 | 172 | 179 | 180 | 181 | 182 | 194 | 195 | 196 | 197 | 198 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 265 | 266 | 267 | 268 | 269 | 277 | 278 | 279 | 280 | 281 | 289 | 290 | 291 | 292 | 293 | 302 | 303 | 304 | 305 | 306 | 316 | 317 | 318 | 319 | 320 | 333 | 334 | 335 | 336 | 337 | 349 | 350 | 351 | 352 | 353 | 373 | 374 | 375 | 376 | 377 | 394 | 395 | 396 | 397 | 398 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 449 | 450 | 451 | 453 | 454 | 582 | -------------------------------------------------------------------------------- /module1/4_constants.php: -------------------------------------------------------------------------------- 1 | 3 | 4 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 17 | 18 | 21 | 22 | 27 | 28 | 29 | 30 | 36 | 37 | 44 | 45 | 46 | 51 | 52 | 63 | 64 | 65 | function testFunction() { 66 | echo MY_CONST; // Works because constants are globally scoped 67 | // echo $myVar; // Might not work if $myVar is defined outside and not passed as an argument or globalized 68 | } 69 | ?> --> 70 | 71 | 72 | 81 | 82 | 83 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /module1/5_comments.php: -------------------------------------------------------------------------------- 1 | 8 | 9 | 17 | 18 | 19 | 34 | 35 | 81 | -------------------------------------------------------------------------------- /module1/6_printing.php: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 8 | 9 | 14 | 15 | 16 | 19 | 20 | 23 | 24 | 25 | 27 | 28 | 35 | 36 | 37 | 38 | 43 | 44 | 55 | 56 | 63 | 64 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 77 | 78 | 80 | 81 | 85 | 86 | 87 | 88 | 95 | 96 | 97 | 98 | 102 | 103 | 104 | 105 | 106 | 111 | 112 | 114 | 115 | 121 | 122 | 123 | 124 | 128 | 129 | 130 | 131 | 132 | 139 | 140 | 141 | 142 | 143 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | -------------------------------------------------------------------------------- /module1/7_arithmetic_operation.php: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 13 | 14 | 15 | 17 | 18 | 19 | 23 | 24 | 25 | 27 | 28 | 33 | 34 | 35 | 37 | 38 | 39 | 43 | 44 | 45 | 47 | 48 | 49 | 53 | 54 | 55 | 59 | 60 | 61 | 68 | 69 | Associativity is often left-to-right for most arithmetic operators, meaning operators are evaluated from left to right. For example: 70 | 71 | 72 | 76 | 77 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /module1/8_number_system.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 17 | 18 | Example: 19 | 20 | 29 | 30 | 31 | 36 | 37 | 41 | 42 | 46 | 47 | 65 | 66 | 67 | 68 | 69 | 84 | 85 | 92 | 93 | 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /module1/9_printf.php: -------------------------------------------------------------------------------- 1 | 8 | 9 | 13 | 14 | 15 | 28 | 29 | 36 | 37 | 42 | 43 | 48 | 49 | 53 | 54 | 55 | 57 | 58 | 64 | 65 | 66 | 71 | 72 | 79 | 80 | 81 | 87 | 88 | 93 | 94 | 100 | 101 | 102 | 103 | 107 | 108 | 113 | 114 | 117 | 118 | 119 | 121 | 122 | 126 | 127 | 129 | 130 | 131 | 133 | 134 | 138 | 139 | 142 | 143 | 144 | 146 | 147 | 152 | 155 | 156 | 157 | 159 | 160 | 167 | 168 | 174 | 175 | 176 | 177 | 179 | 180 | 184 | 185 | 186 | 188 | 189 | 192 | 193 | 198 | 199 | 203 | 204 | 205 | 207 | 208 | 212 | 213 | 217 | 218 | 219 | 221 | 222 | 223 | 227 | 228 | 231 | 232 | 233 | 235 | 236 | 240 | 241 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | -------------------------------------------------------------------------------- /module1/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 39 | 40 | 41 | 42 | 43 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 69 | 70 | 71 | 72 | 77 | 78 | 79 | 80 | 87 | 88 | 89 | 90 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 110 | 111 | 112 | 113 | 116 | 117 | 118 | 125 | 126 | 127 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 145 | 146 | 147 | 148 | 152 | 153 | 154 | 155 | 156 | 161 | 162 | 163 | 164 | 165 | 169 | 170 | 171 | 173 | 174 | 175 | 179 | 180 | 181 | 182 | 183 | 190 | 191 | 195 | 196 | 197 | 210 | 211 | 218 | 219 | 220 | 221 | 222 | 223 | 231 | 232 | 233 | 234 | 235 | 245 | 246 | 274 | 275 | 285 | 286 | 295 | 296 | 300 | 301 | 310 | 311 | 312 | 314 | 315 | 323 | 324 | 325 | 326 | 327 | 334 | 335 | 336 | 337 | 338 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | -------------------------------------------------------------------------------- /module1/main.php: -------------------------------------------------------------------------------- 1 | = 18) { 177 | // echo "You are eligible to vote."; 178 | // } 179 | 180 | 181 | 182 | 183 | 184 | 185 | /* 186 | Comparison Operators: 187 | 188 | == : Equal to 189 | != : Not equal to 190 | < : Less than 191 | > : Greater than 192 | <= : Less than or equal to 193 | >= : Greater than or equal to 194 | Here are some ✅Examples using these operators: 195 | 196 | 197 | */ 198 | 199 | 200 | 201 | // $number = 10; 202 | 203 | // if ($number == 10) { 204 | // echo "The number is 10."; 205 | // } 206 | 207 | // if ($number != 15) { 208 | // echo "The number is not 15."; 209 | // } 210 | 211 | // if ($number < 20) { 212 | // echo "The number is less than 20."; 213 | // } 214 | 215 | // if ($number > 5) { 216 | // echo "The number is greater than 5."; 217 | // } 218 | 219 | // if ($number <= 10) { 220 | // echo "The number is 10 or less."; 221 | // } 222 | 223 | // if ($number >= 9) { 224 | // echo "The number is 9 or more."; 225 | // } 226 | 227 | 228 | /* 229 | logical operators: 230 | 231 | 232 | && : AND 233 | || : OR 234 | ! : NOT 235 | 236 | */ 237 | 238 | // ✅Example 15 239 | 240 | 241 | // $age = 20; 242 | // $hasID = true; 243 | 244 | // if ($age >= 18 && $hasID) { 245 | // echo "You can enter the club."; 246 | // } 247 | 248 | 249 | 250 | // ✅Example 16 251 | 252 | // $isWeekend = true; 253 | // $hasHoliday = false; 254 | 255 | // if ($isWeekend || $hasHoliday) { 256 | // echo "You don't have to go to work."; 257 | // } 258 | 259 | 260 | 261 | 262 | // ✅Example 17 263 | 264 | // $isRaining = false; 265 | 266 | // if (!$isRaining) { 267 | // echo "You don't need an umbrella."; 268 | // } 269 | 270 | 271 | 272 | 273 | // ✅Example 18 274 | 275 | // $age=19; 276 | 277 | // $status = ($age < 18) ? "minor" : "adult"; 278 | // echo $status; 279 | 280 | 281 | 282 | // ✅Example 19 283 | 284 | // $day = 3; // Wednesday 285 | 286 | // switch ($day) { 287 | // case 1: 288 | // echo "Monday"; 289 | // break; 290 | // case 2: 291 | // echo "Tuesday"; 292 | // break; 293 | // case 3: 294 | // echo "Wednesday"; 295 | // break; 296 | // case 4: 297 | // echo "Thursday"; 298 | // break; 299 | // case 5: 300 | // echo "Friday"; 301 | // break; 302 | // case 6: 303 | // echo "Saturday"; 304 | // break; 305 | // case 7: 306 | // echo "Sunday"; 307 | // break; 308 | // default: 309 | // echo "Invalid day number!"; 310 | // } 311 | 312 | 313 | 314 | /* 315 | Formatting Output Using Escape Characters: 316 | Escape characters are used to represent certain special characters in strings. These characters are prefixed with a backslash \. 317 | 318 | Some commonly used escape characters in PHP are: 319 | 320 | \n: Newline character 321 | \t: Tab character 322 | \": Double quote 323 | \': Single quote 324 | \\: Backslash 325 | Here's an ✅Example demonstrating the use of these escape characters: 326 | */ 327 | 328 | // ✅Example 20 329 | 330 | // echo "Hello\tWorld!\n I love bangladesh"; // Outputs: Hello World! (with a tab space and then moves to the next line) 331 | 332 | // echo "She said, \"Hello!\""; // Outputs: She said, "Hello!" 333 | 334 | // echo 'It\'s a beautiful day!'; // Outputs: It's a beautiful day! 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | -------------------------------------------------------------------------------- /module1/project/calculator/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Basic Calculator 8 | 11 | 12 | 13 |
14 |

Basic Calculator

15 |
16 |
17 |
18 |
27 | 28 |
29 |
30 | 69 |
70 |
71 | 72 | -------------------------------------------------------------------------------- /module1/project/calculator/styles.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Arial, sans-serif; 3 | text-align: center; 4 | } 5 | 6 | .container { 7 | margin: 50px auto; 8 | width: 300px; 9 | border: 1px solid #ccc; 10 | padding: 20px; 11 | border-radius: 5px; 12 | box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); 13 | } 14 | 15 | input[type="number"], select { 16 | width: 100%; 17 | padding: 8px; 18 | margin-bottom: 10px; 19 | border: 1px solid #ccc; 20 | border-radius: 3px; 21 | } 22 | 23 | button { 24 | background-color: #007BFF; 25 | color: white; 26 | border: none; 27 | padding: 10px 20px; 28 | border-radius: 3px; 29 | cursor: pointer; 30 | } 31 | 32 | #result { 33 | margin-top: 20px; 34 | font-size: 18px; 35 | } -------------------------------------------------------------------------------- /module2/1_agenda.js: -------------------------------------------------------------------------------- 1 | // Module: PHP Looping, Functions, and Recursion 2 | // 1. Understanding Loops in PHP 3 | // Introduction to loops in PHP 4 | // Different types of loops in PHP: 5 | // For loop 6 | // While loop 7 | // Do-while loop 8 | // Foreach loop (brief introduction) 9 | // Nested loops: Concept and usage 10 | 11 | // 2. Advanced Loop Controls 12 | // Multiple stepping in For loops: Definition and implementation 13 | // The continue statement: Usage and examples 14 | // The break statement: Usage and examples 15 | // Hands-on: Printing the Fibonacci series using loops 16 | 17 | // 3. Functions in PHP 18 | // Introduction to functions in PHP 19 | // Declaring and executing functions: Syntax and examples 20 | // Parameters and arguments in functions: 21 | // Definition and distinction 22 | // Setting default parameter values 23 | // Function return types: Specification and enforcement 24 | // Type hinting in functions: Utilization and benefits 25 | 26 | // 4. Advanced Function Handling 27 | // Variadic functions: Accepting unlimited arguments in functions 28 | // Decomposing large functions: 29 | // Benefits of dividing a large function into smaller functions 30 | // Strategies for breaking down complex functions 31 | // Recursive functions: 32 | // Understanding recursion and its applications 33 | // Hands-on: Printing the Fibonacci series using recursive functions 34 | 35 | // 5. Variable Scope in PHP Functions 36 | // Local vs global variable scope 37 | // Understanding the global keyword 38 | // The static keyword: Usage and implications 39 | 40 | // 6. Project and Recap 41 | // Recap of the concepts learned 42 | // Project: Creating a comprehensive script that incorporates loops and functions 43 | // Q&A session and feedback gathering 44 | // Additional Resources 45 | // Reading materials 46 | // Online forums and communities for PHP developers 47 | // Recommended practices for coding in PHP 48 | // I would recommend incorporating practical examples, coding exercises, and perhaps a small project at the end of the module to help consolidate the learning. It will provide the learners with an opportunity to apply the knowledge they have acquired throughout the module. Make sure to include various examples and possibly create quizzes or assignments to evaluate understanding progressively. -------------------------------------------------------------------------------- /module2/2_loop.js: -------------------------------------------------------------------------------- 1 | // Introduction to Loops in PHP 2 | // In PHP, a loop is a control structure used to execute a block of code repeatedly as long as a specified condition is true. Loops are essential in programming as they help you to execute a set of statements multiple times, which helps in reducing code redundancy. 3 | 4 | //✅ Different Types of Loops in PHP 5 | // For Loop 6 | // A for loop is used when you know in advance how many times you want to execute a statement or a block of statements. 7 | 8 | // Here is the syntax for the for loop: 9 | 10 | 11 | // for (initialization; condition; updater) { 12 | // // code to be executed; 13 | // } 14 | // Example: 15 | 16 | 17 | // for ($i = 0; $i < 5; $i++) { 18 | // echo $i . "
"; 19 | // } 20 | // In the above example: 21 | 22 | // Initialization: $i = 0 (We start counting from 0) 23 | // Condition: $i < 5 (The loop will continue as long as $i is less than 5) 24 | // Updater: $i++ (After each loop, $i is incremented by 1) 25 | // While Loop 26 | // A while loop will execute a block of code as long as the specified condition is true. 27 | 28 | // Here is the syntax for the while loop: 29 | 30 | 31 | // ✅while (condition) { 32 | // // code to be executed; 33 | // } 34 | // Example: 35 | 36 | 37 | // $i = 0; 38 | // while ($i < 5) { 39 | // echo $i . "
"; 40 | // $i++; 41 | // } 42 | 43 | //✅ Do-While Loop 44 | // A do-while loop is similar to a while loop, but it will execute the block of code at least once before checking the condition. 45 | 46 | // Here is the syntax for the do-while loop: 47 | 48 | 49 | // do { 50 | // // code to be executed; 51 | // } while (condition); 52 | // Example: 53 | 54 | 55 | // $i = 0; 56 | // do { 57 | // echo $i . "
"; 58 | // $i++; 59 | // } while ($i < 5); 60 | 61 | // ✅Foreach Loop 62 | // The foreach loop works only on arrays and is used to loop through each key/value pair in an array. 63 | 64 | // Here is the syntax for the foreach loop: 65 | 66 | 67 | // foreach ($array as $value) { 68 | // // code to be executed; 69 | // } 70 | // Example: 71 | 72 | 73 | // $arr = array(1, 2, 3, 4, 5); 74 | // foreach ($arr as $value) { 75 | // echo $value . "
"; 76 | // } 77 | // Nested Loops 78 | // Nested loops are loops within loops. It means you can use one loop inside another loop. 79 | 80 | // Here is the syntax for the nested loops: 81 | 82 | 83 | // for (initialization; condition; updater) { 84 | // for (initialization; condition; updater) { 85 | // // code to be executed; 86 | // } 87 | // } 88 | // Example: 89 | 90 | 91 | // for ($i = 0; $i < 3; $i++) { 92 | // for ($j = 0; $j < 3; $j++) { 93 | // echo "$i, $j
"; 94 | // } 95 | // } 96 | 97 | // In this nested loop example, we have a for loop inside another for loop, creating a grid-like pattern of output values. -------------------------------------------------------------------------------- /module2/3_forloop.js: -------------------------------------------------------------------------------- 1 | //👉 PHP for Loop Syntax 2 | 3 | // The general syntax for a for loop in PHP is as follows: 4 | 5 | 6 | //✅ for (initialize; condition; iteration) { 7 | // // code to be executed 8 | // } 9 | // Initialize: This is where you set your loop counter to its initial value. 10 | // Condition: This is a Boolean expression that the PHP engine checks before each iteration of the loop. If this expression evaluates to true, the loop continues; if it evaluates to false, the loop ends. 11 | // Iteration: This is where you define how your loop counter should be modified after each iteration of the loop. 12 | // PHP for Loop Examples 13 | 14 | 15 | //✅ Example 1: Simple for Loop 16 | // Here is a simple example of a for loop that prints numbers from 1 to 10: 17 | 18 | 19 | // for ($i = 1; $i <= 10; $i++) { 20 | // echo $i . "
"; 21 | // } 22 | 23 | 24 | // In this loop: 25 | 26 | // We initialize the variable $i to 1. 27 | // We specify the condition $i <= 10, so the loop will continue as long as $i is less than or equal to 10. 28 | // We increase the value of $i by 1 each time the loop iterates, using the ++ operator (which is a shorthand for $i = $i + 1). 29 | 30 | 31 | // ✅Example 2: Looping Through an Array 32 | // Here we will loop through each element in an array and print it: 33 | 34 | 35 | // $array = array("apple", "banana", "cherry", "date", "elderberry"); 36 | 37 | // for ($i = 0; $i < count($array); $i++) { 38 | // echo $array[$i] . "
"; 39 | // } 40 | 41 | 42 | // In this loop: 43 | 44 | // We initialize the variable $i to 0 because arrays in PHP are zero-indexed, meaning that the first element in the array has an index of 0. 45 | // We use the count() function to get the number of elements in the array, and continue the loop as long as $i is less than the number of elements in the array. 46 | // We use the $i variable to access each element in the array using its index. 47 | 48 | 49 | // ✅Example 3: Skipping Iterations with continue 50 | // In this example, we'll use a for loop to print numbers from 1 to 10, but we'll skip even numbers using a continue statement: 51 | 52 | 53 | // for ($i = 1; $i <= 10; $i++) { 54 | // if ($i % 2 == 0) { 55 | // continue; 56 | // } 57 | // echo $i . "
"; 58 | // } 59 | 60 | 61 | // In this loop: 62 | 63 | // We use an if statement and the modulus operator (%) to check if $i is even. If it is, we use the continue statement to skip the rest of the current iteration and move to the next iteration of the loop. 64 | // If $i is not even, we print its value. 65 | // I hope this provides a clear introduction to for loops in PHP! Try creating your own for loops to further understand how they work. Let me know if you have any questions. 66 | 67 | 68 | 69 | 70 | 71 | 72 | //✅ Example 1: Multiplication Table 73 | // Creating a multiplication table using nested for loops. 74 | 75 | 76 | // echo ""; 77 | // for ($i = 1; $i <= 10; $i++) { 78 | // echo ""; 79 | // for ($j = 1; $j <= 10; $j++) { 80 | // echo ""; 81 | // } 82 | // echo ""; 83 | // } 84 | // echo "
" . $i * $j . "
"; 85 | 86 | 87 | //✅ Example 2: Reversing an Array 88 | // Using a for loop to reverse the elements of an array. 89 | 90 | 91 | // $arr = [1, 2, 3, 4, 5]; 92 | // $reversedArr = []; 93 | 94 | // for ($i = count($arr) - 1; $i >= 0; $i--) { 95 | // $reversedArr[] = $arr[$i]; 96 | // } 97 | 98 | // print_r($reversedArr); 99 | 100 | // ✅Example 3: Fibonacci Series 101 | // Generating the first 10 numbers in the Fibonacci series using a for loop. 102 | 103 | 104 | // $a = 0; 105 | // $b = 1; 106 | 107 | // echo "$a, $b"; 108 | 109 | // for ($i = 1; $i <= 8; $i++) { 110 | // $temp = $a; 111 | // $a = $b; 112 | // $b = $temp + $b; 113 | // echo ", $b"; 114 | // } 115 | 116 | //✅ Example 4: Factorial 117 | // Calculating the factorial of a number using a for loop. 118 | 119 | 120 | // $number = 5; 121 | // $factorial = 1; 122 | 123 | // for ($i = 1; $i <= $number; $i++) { 124 | // $factorial *= $i; 125 | // } 126 | 127 | // echo "The factorial of $number is $factorial."; 128 | 129 | 130 | // ✅Example 5: Sum of Array Elements 131 | // Using a for loop to find the sum of all elements in an array. 132 | 133 | 134 | // $arr = [1, 2, 3, 4, 5]; 135 | // $sum = 0; 136 | 137 | // for ($i = 0; $i < count($arr); $i++) { 138 | // $sum += $arr[$i]; 139 | // } 140 | 141 | // echo "The sum of the array elements is $sum."; 142 | 143 | 144 | // ✅Example 6: Creating an HTML List from an Array 145 | // Using a for loop to create an HTML list from an array. 146 | 147 | // php 148 | // Copy code 149 | // $arr = ['Apple', 'Banana', 'Cherry']; 150 | // echo ""; 155 | 156 | //✅ Example 7: Prime Numbers 157 | // Using a for loop to find and display the first N prime numbers. 158 | 159 | 160 | // $n = 10; 161 | // $count = 0; 162 | // $num = 2; 163 | 164 | // while ($count < $n){ 165 | // $div_count=0; 166 | 167 | // for ($i = 1; $i <= $num; $i++){ 168 | // if (($num % $i) == 0) { 169 | // $div_count++; 170 | // } 171 | // } 172 | 173 | // if ($div_count < 3) { 174 | // echo $num . ", "; 175 | // $count = $count + 1; 176 | // } 177 | // $num = $num + 1; 178 | // } 179 | 180 | // ✅Example 8: Building a Pyramid Pattern 181 | // Using a for loop to build a pyramid pattern with asterisks (*). 182 | 183 | 184 | // $height = 5; 185 | 186 | // for ($i = 1; $i <= $height; $i++) { 187 | // echo str_repeat(' ', $height - $i); 188 | // echo str_repeat('*', 2 * $i - 1); 189 | // echo "
"; 190 | // } 191 | 192 | 193 | // ✅Example 9: Display Array Keys and Values 194 | // Using a for loop to display the keys and values of an associative array. 195 | 196 | // php 197 | // Copy code 198 | // $arr = ["name" => "Alice", "age" => 25, "city" => "New York"]; 199 | // $keys = array_keys($arr); 200 | 201 | // for ($i = 0; $i < count($arr); $i++) { 202 | // echo $keys[$i] . ": " . $arr[$keys[$i]] . "
"; 203 | // } 204 | 205 | 206 | //✅ Example 10: Calculating the Exponential of a Number 207 | // Using a for loop to calculate the exponential of a number (n^x). 208 | 209 | 210 | // $n = 2; 211 | // $x = 5; 212 | // $result = 1; 213 | 214 | // for ($i = 0; $i < $x; $i++) { 215 | // $result *= $n; 216 | // } 217 | 218 | // echo "$n raised to the power $x is: $result."; 219 | 220 | // Each of these examples illustrates a different application of for loops in PHP. They demonstrate various operations such as arithmetic calculations, working with arrays, and generating HTML output. You can run each of these scripts in a PHP environment to see them in action and better understand how for loops work. Let me know if you have any questions about any of the examples! 221 | 222 | // ✅Example 1: Generating Dynamic Menu Items 223 | // In a web application, dynamically generating a navigation menu from a database or array. 224 | 225 | 226 | // $menuItems = ['Home', 'About Us', 'Services', 'Contact Us']; 227 | 228 | // echo ""; 233 | 234 | 235 | // ✅Example 2: Pagination 236 | // Implementing pagination in a PHP web application to divide content into several pages. 237 | 238 | 239 | // $totalPages = 50; 240 | // $currentPage = 1; 241 | 242 | // echo ""; 248 | 249 | // ✅Example 3: Generating Form Fields Dynamically 250 | // Creating a form with a dynamic number of input fields based on user input or configuration settings. 251 | 252 | 253 | // $fieldCount = 5; 254 | 255 | // for ($i = 0; $i < $fieldCount; $i++) { 256 | // echo "
"; 257 | // } 258 | 259 | //✅ Example 4: Image Gallery 260 | // Displaying a gallery of images by looping through an array of image URLs. 261 | 262 | 263 | // $imageUrls = [ 264 | // 'path/to/image1.jpg', 265 | // 'path/to/image2.jpg', 266 | // 'path/to/image3.jpg' 267 | // ]; 268 | 269 | // echo ""; 274 | 275 | // ✅Example 5: Outputting a Calendar 276 | // Creating a calendar where you loop through the days of the month to output a visual calendar. 277 | 278 | 279 | // $daysInMonth = date('t'); 280 | // echo ""; 281 | // for ($i = 1; $i <= $daysInMonth; $i++) { 282 | // echo ""; 283 | // if ($i % 7 == 0) { 284 | // echo ""; 285 | // } 286 | // } 287 | // echo "
$i
"; 288 | 289 | // ✅Example 6: Exporting Data to CSV 290 | // Looping through a database result set to export data to a CSV file. 291 | 292 | 293 | // $data = [ 294 | // ['Alice', '28', 'New York'], 295 | // ['Bob', '24', 'Los Angeles'], 296 | // ]; 297 | 298 | // $fp = fopen('file.csv', 'w'); 299 | 300 | // for ($i = 0; $i < count($data); $i++) { 301 | // fputcsv($fp, $data[$i]); 302 | // } 303 | 304 | // fclose($fp); 305 | 306 | // ✅Example 7: Creating a Tag Cloud 307 | // Building a tag cloud from an array of tags, where the font size of each tag is determined by its frequency of occurrence. 308 | 309 | 310 | // $tags = ['PHP', 'HTML', 'CSS', 'JavaScript', 'PHP', 'HTML']; 311 | 312 | // $tagCounts = array_count_values($tags); 313 | 314 | // echo "
"; 315 | // foreach ($tagCounts as $tag => $count) { 316 | // $fontSize = 10 + $count * 5; 317 | // echo "$tag "; 318 | // } 319 | // echo "
"; 320 | 321 | 322 | // ✅Example 8: Generating Report Tables 323 | // Creating a table to display report data retrieved from a database. 324 | 325 | 326 | // $reportData = [ 327 | // ['John Doe', 'Sales', '$1000'], 328 | // ['Jane Doe', 'Marketing', '$1200'], 329 | // ]; 330 | 331 | // echo ""; 332 | // for ($i = 0; $i < count($reportData); $i++) { 333 | // echo ""; 334 | // for ($j = 0; $j < count($reportData[$i]); $j++) { 335 | // echo ""; 336 | // } 337 | // echo ""; 338 | // } 339 | // echo "
{$reportData[$i][$j]}
"; 340 | 341 | 342 | // ✅Example 9: Generating Breadcrumbs 343 | // Dynamically generating breadcrumbs for a website to improve navigation. 344 | 345 | 346 | // $breadcrumbs = ['Home', 'Products', 'Laptops']; 347 | 348 | // echo ""; 356 | 357 | 358 | //✅ Example 10: Sending Bulk Emails 359 | // Using a for loop to send emails to multiple recipients in a bulk email operation. 360 | 361 | 362 | // $emailAddresses = ['user1@example.com', 'user2@example.com']; 363 | 364 | // for ($i = 0; $i < count($emailAddresses); $i++) { 365 | // mail($emailAddresses[$i], 'Subject', 'Message'); 366 | // } 367 | 368 | 369 | // Each example demonstrates how for loops can be used to facilitate different functionalities in a real-world PHP project, be it displaying data, exporting files, generating HTML structures, or automating repetitive tasks. You would replace the static arrays with dynamic data from your database or API responses in a real-world scenario. Let me know if you have any questions or need further clarification! 370 | 371 | 372 | // Challenge 1: Basic Loop 373 | // Write a PHP for loop that prints the numbers from 1 to 10. 374 | 375 | // Challenge 2: Even Numbers 376 | // Write a PHP for loop that prints all even numbers between 20 and 40. 377 | 378 | // Challenge 3: Odd Numbers 379 | // Write a PHP for loop that prints all odd numbers between 15 and 35. 380 | 381 | // Challenge 4: Sum of Numbers 382 | // Write a PHP for loop that calculates and prints the sum of all numbers from 1 to 100. 383 | 384 | // Challenge 5: Multiplication Table 385 | // Write a PHP for loop that generates and prints the multiplication table for a given number. For example, if the input is 5, it should print the table for 5 (5x1, 5x2, ..., 5x10). 386 | 387 | // Challenge 6: Factorial 388 | // Write a PHP for loop that calculates and prints the factorial of a given number. The factorial of a number n is the product of all positive integers from 1 to n. 389 | 390 | // Challenge 7: Reverse String 391 | // Write a PHP for loop that takes a string as input and prints the characters of the string in reverse order. 392 | 393 | // Challenge 8: Countdown 394 | // Write a PHP for loop that counts down from 10 to 1 and prints the countdown values. 395 | 396 | // Challenge 9: Pattern Printing 397 | // Write a PHP for loop that prints the following pattern: 398 | 399 | 400 | // * 401 | // ** 402 | // *** 403 | // **** 404 | // ***** 405 | 406 | 407 | // Challenge 10: Fibonacci Sequence 408 | // Write a PHP for loop that generates and prints the first 20 numbers in the Fibonacci sequence. In the Fibonacci sequence, each number is the sum of the two preceding ones (starting from 0 and 1). 409 | 410 | // These challenges cover a range of scenarios where for loops are commonly used in PHP. They should help you assess and strengthen your understanding of for loops in PHP. 411 | 412 | 413 | 414 | // Here are the solutions to the 10 coding challenges for assessing the concept of the for loop in PHP: 415 | 416 | // Challenge 1: Basic Loop 417 | 418 | 419 | // for ($i = 1; $i <= 10; $i++) { 420 | // echo $i . " "; 421 | // } 422 | 423 | 424 | // Challenge 2: Even Numbers 425 | 426 | 427 | // for ($i = 20; $i <= 40; $i += 2) { 428 | // echo $i . " "; 429 | // } 430 | 431 | 432 | // Challenge 3: Odd Numbers 433 | 434 | 435 | // for ($i = 15; $i <= 35; $i += 2) { 436 | // echo $i . " "; 437 | // } 438 | 439 | 440 | 441 | // Challenge 4: Sum of Numbers 442 | 443 | 444 | // $sum = 0; 445 | // for ($i = 1; $i <= 100; $i++) { 446 | // $sum += $i; 447 | // } 448 | // echo $sum; 449 | 450 | 451 | 452 | // Challenge 5: Multiplication Table 453 | 454 | 455 | // $number = 5; 456 | // for ($i = 1; $i <= 10; $i++) { 457 | // echo $number . " x " . $i . " = " . ($number * $i) . "\n"; 458 | // } 459 | 460 | 461 | // Challenge 6: Factorial 462 | 463 | 464 | // $number = 5; 465 | // $factorial = 1; 466 | // for ($i = 1; $i <= $number; $i++) { 467 | // $factorial *= $i; 468 | // } 469 | // echo "Factorial of " . $number . " is " . $factorial; 470 | 471 | 472 | // Challenge 7: Reverse String 473 | 474 | 475 | // $string = "Hello, World!"; 476 | // $length = strlen($string); 477 | // for ($i = $length - 1; $i >= 0; $i--) { 478 | // echo $string[$i]; 479 | // } 480 | 481 | 482 | // Challenge 8: Countdown 483 | 484 | 485 | // for ($i = 10; $i >= 1; $i--) { 486 | // echo $i . " "; 487 | // } 488 | 489 | 490 | // Challenge 9: Pattern Printing 491 | 492 | 493 | // for ($i = 1; $i <= 5; $i++) { 494 | // for ($j = 1; $j <= $i; $j++) { 495 | // echo "*"; 496 | // } 497 | // echo "\n"; 498 | // } 499 | 500 | 501 | // Challenge 10: Fibonacci Sequence 502 | 503 | 504 | // $first = 0; 505 | // $second = 1; 506 | // for ($i = 1; $i <= 20; $i++) { 507 | // echo $first . " "; 508 | // $next = $first + $second; 509 | // $first = $second; 510 | // $second = $next; 511 | // } 512 | 513 | 514 | // These solutions demonstrate how to use for loops in various scenarios in PHP. You can run these code snippets to see the output and further understand how for loops work in each case. -------------------------------------------------------------------------------- /module2/4_break_continue.js: -------------------------------------------------------------------------------- 1 | // 👉In PHP, the for loop is a control structure that allows you to execute a block of code repeatedly based on a specified number of iterations. The continue and break statements are used within loops to control the flow of execution. 2 | 3 | // Let's start with the break statement: 4 | 5 | // ✅break Statement: 6 | // The break statement is used to exit the loop prematurely. When a break statement is encountered within a loop, the loop is immediately terminated, and the program continues with the code after the loop. It's often used when a certain condition is met, and you want to exit the loop early. 7 | 8 | // Here's an example of using break in a for loop: 9 | 10 | 11 | // for ($i = 1; $i <= 10; $i++) { 12 | // if ($i == 5) { 13 | // break; // Exit the loop when $i equals 5 14 | // } 15 | // echo $i . " "; 16 | // } 17 | 18 | // // Output: 1 2 3 4 19 | 20 | 21 | // In this example, the loop runs from 1 to 10. When $i equals 5, the break statement is executed, and the loop is terminated. 22 | 23 | // ✅continue Statement: 24 | // The continue statement is used to skip the rest of the current iteration of the loop and move to the next iteration. It's handy when you want to skip certain iterations based on a condition but continue looping. 25 | 26 | // Here's an example of using continue in a for loop: 27 | 28 | 29 | // for ($i = 1; $i <= 10; $i++) { 30 | // if ($i % 2 == 0) { 31 | // continue; // Skip even numbers 32 | // } 33 | // echo $i . " "; 34 | // } 35 | 36 | // // Output: 1 3 5 7 9 37 | 38 | 39 | // In this example, the loop runs from 1 to 10. When $i is an even number (i.e., $i % 2 == 0), the continue statement is executed, and that iteration of the loop is skipped. 40 | 41 | // Remember that break and continue can be used in different types of loops (not just for loops) and are not limited to PHP. They are essential control flow tools in many programming languages. 42 | 43 | // I hope these examples help clarify the use of break and continue within for loops in PHP. If you have any further questions or need more examples, feel free to ask! 44 | 45 | 46 | 47 | 48 | // ✅Example 1: Skipping Weekends 49 | 50 | // for ($day = 1; $day <= 7; $day++) { 51 | // if (date('N', strtotime("2023-09-$day")) >= 6) { 52 | // continue; // Skip Saturday (6) and Sunday (7) 53 | // } 54 | // echo "Do work on day $day.\n"; 55 | // } 56 | 57 | 58 | // In this example, we use continue to skip the weekend days (Saturday and Sunday) when processing a week. 59 | 60 | // ✅Example 2: Searching for a Specific Value 61 | 62 | // $numbers = [2, 4, 6, 8, 10, 12, 14, 16]; 63 | // $searchValue = 10; 64 | 65 | // for ($i = 0; $i < count($numbers); $i++) { 66 | // if ($numbers[$i] === $searchValue) { 67 | // echo "Found $searchValue at index $i.\n"; 68 | // break; // Exit the loop when the value is found 69 | // } 70 | // } 71 | 72 | // Here, break is used to stop the loop as soon as the desired value is found. 73 | 74 | // ✅Example 3: Processing Files Until a Condition is Met 75 | 76 | // $files = glob('*.txt'); 77 | 78 | // foreach ($files as $file) { 79 | // if (filesize($file) > 1000) { 80 | // echo "Found a large file: $file.\n"; 81 | // break; // Stop processing when a large file is found 82 | // } 83 | // processFile($file); 84 | // } 85 | 86 | 87 | // This code iterates through a list of text files and breaks the loop if it encounters a file larger than 1000 bytes. 88 | 89 | // ✅Example 4: Validating User Input 90 | 91 | // $userInput = ['John', 'Doe', 'johndoe.com']; 92 | 93 | // for ($i = 0; $i < count($userInput); $i++) { 94 | // if (!isValid($userInput[$i])) { 95 | // echo "Invalid input: " . $userInput[$i] . "\n"; 96 | // break; // Stop processing invalid input 97 | // } 98 | // echo "Valid input: " . $userInput[$i] . "\n"; 99 | // } 100 | 101 | // Here, break is used to exit the loop when invalid user input is encountered during validation. 102 | 103 | // ✅Example 5: Early Termination in a Game 104 | 105 | // $gameOver = false; 106 | 107 | // for ($turn = 1; $turn <= 10; $turn++) { 108 | // if (isGameOver()) { 109 | // $gameOver = true; 110 | // break; // Exit the loop when the game is over 111 | // } 112 | // playTurn($turn); 113 | // } 114 | 115 | // if ($gameOver) { 116 | // echo "Game over!\n"; 117 | // } 118 | 119 | // In a game simulation, break is used to stop the loop when the game is over, avoiding unnecessary turns. 120 | 121 | // ✅Example 6: Handling Exceptional Cases 122 | 123 | // $numbers = [1, 3, 5, 7, 9, 11, 13, 15]; 124 | 125 | // for ($i = 0; $i < count($numbers); $i++) { 126 | // if ($numbers[$i] % 2 == 0) { 127 | // echo "Unexpected even number found: " . $numbers[$i] . "\n"; 128 | // continue; // Skip even numbers 129 | // } 130 | // echo "Processing odd number: " . $numbers[$i] . "\n"; 131 | // } 132 | // Here, continue is used to handle exceptional cases (even numbers) differently from the regular processing. 133 | 134 | // ✅Example 7: Skipping Header Rows in CSV Processing 135 | 136 | // $rows = file('data.csv'); 137 | 138 | // for ($i = 0; $i < count($rows); $i++) { 139 | // if ($i === 0) { 140 | // continue; // Skip the header row 141 | // } 142 | // processCSVRow($rows[$i]); 143 | // } 144 | 145 | // This code skips the header row when processing data from a CSV file using continue. 146 | 147 | // ✅Example 8: Early Exit in a Loop with Multiple Conditions 148 | 149 | // $items = getItems(); 150 | 151 | // for ($i = 0; $i < count($items); $i++) { 152 | // if (isOutOfStock($items[$i])) { 153 | // echo "Item out of stock: " . $items[$i] . "\n"; 154 | // break; // Exit the loop when an item is out of stock 155 | // } 156 | // if (isExpired($items[$i])) { 157 | // echo "Item expired: " . $items[$i] . "\n"; 158 | // break; // Exit the loop when an item is expired 159 | // } 160 | // processItem($items[$i]); 161 | // } 162 | 163 | // In this scenario, break is used to exit the loop if either an item is out of stock or an item is expired. 164 | 165 | // ✅Example 9: Handling Errors While Processing Data 166 | 167 | // $data = fetchData(); 168 | 169 | // for ($i = 0; $i < count($data); $i++) { 170 | // if (!isValidData($data[$i])) { 171 | // echo "Invalid data encountered. Skipping...\n"; 172 | // continue; // Skip invalid data 173 | // } 174 | // processValidData($data[$i]); 175 | // } 176 | // Here, continue is used to skip invalid data records while processing a data set. 177 | 178 | // ✅Example 10: Implementing Pagination 179 | 180 | // $itemsPerPage = 10; 181 | // $totalItems = getTotalItems(); 182 | 183 | // for ($page = 1; $page <= ceil($totalItems / $itemsPerPage); $page++) { 184 | // // Display items for the current page 185 | // $start = ($page - 1) * $itemsPerPage; 186 | // $end = min($start + $itemsPerPage, $totalItems); 187 | 188 | // for ($i = $start; $i < $end; $i++) { 189 | // displayItem($i); 190 | // } 191 | 192 | // if (userWantsToQuit()) { 193 | // break; // Exit pagination loop if the user wants to quit 194 | // } 195 | // } 196 | 197 | 198 | // In this example, break is used to exit the pagination loop if the user decides to quit the pagination process. 199 | 200 | // These examples illustrate how break and continue statements can be applied in real-world scenarios within for loops in PHP to control flow and make your code more efficient and responsive to specific conditions. -------------------------------------------------------------------------------- /module2/5_fibonacci.js: -------------------------------------------------------------------------------- 1 | // The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. Here's how you can do it with a loop in PHP: 2 | 3 | 4 | // 35 | 36 | 37 | 38 | // Here's what this PHP code does: 39 | 40 | // It defines a function called printFibonacci that takes the number of terms you want to print as a parameter. 41 | 42 | // Inside the function, it initializes the first two terms of the Fibonacci sequence, $first and $second, as 0 and 1. 43 | 44 | // It checks if the input $numTerms is less than or equal to 0 and displays an error message if it is. 45 | 46 | // It then prints the first two terms. 47 | 48 | // Using a for loop, it calculates and prints the rest of the terms in the Fibonacci sequence up to the specified number of terms. 49 | 50 | // Finally, it calls the printFibonacci function with the desired number of terms, which you can change by modifying the $numTerms variable. 51 | 52 | // Simply copy and paste this code into a PHP file (e.g., fibonacci.php) and run it to see the Fibonacci series printed for the specified number of terms. -------------------------------------------------------------------------------- /module2/6_function.js: -------------------------------------------------------------------------------- 1 | //👉 Introduction to Functions in PHP: 2 | 3 | // A function in PHP is a block of reusable code that performs a specific task. Functions are essential for modularizing your code and making it more organized. 4 | 5 | 6 | // // Defining a simple function 7 | // function greet() { 8 | // echo "Hello, World!"; 9 | // } 10 | 11 | // Calling the function 12 | // greet(); 13 | 14 | // 2. ✅Declaring and Executing Functions: 15 | // To declare a function, use the function keyword followed by the function name and a pair of parentheses. To execute a function, simply call its name followed by parentheses. 16 | 17 | // 3.✅ Parameters and Arguments in Functions: 18 | // Parameters are placeholders for values that a function will receive and work with. Arguments are the actual values passed to the function when it's called. 19 | 20 | 21 | // function greetWithName($name) { 22 | // echo "Hello, $name!"; 23 | // } 24 | 25 | // // Calling the function with an argument 26 | // greetWithName("Alice"); 27 | 28 | // 4.✅ Setting Default Parameter Values: 29 | // You can set default values for function parameters. If an argument isn't provided when calling the function, it will use the default value. 30 | 31 | 32 | // function greetWithDefault($name = "Guest") { 33 | // echo "Hello, $name!"; 34 | // } 35 | 36 | // // Calling the function without an argument 37 | // greetWithDefault(); // Output: Hello, Guest 38 | 39 | // 5. ✅Function Return Types: 40 | // PHP 7.0 introduced return type declarations, allowing you to specify the type of value a function should return. 41 | 42 | 43 | // function add($a, $b): int { 44 | // return $a + $b; 45 | // } 46 | 47 | // $result = add(3, 4); // $result is an integer 48 | 49 | // 6. ✅Type Hinting in Functions: 50 | // Type hinting allows you to specify the expected data type of a function's parameters. This helps in enforcing data integrity. 51 | 52 | 53 | // function divide(int $a, int $b): float { 54 | // if ($b === 0) { 55 | // throw new Exception("Division by zero is not allowed."); 56 | // } 57 | // return $a / $b; 58 | // } 59 | 60 | // $result = divide(10, 2); // $result is a float 61 | 62 | // Type hinting ensures that the provided arguments match the expected data types, and it also provides better code readability. 63 | 64 | // In summary, functions in PHP are essential for code organization and reusability. You can define functions, pass parameters with default values, specify return types, and use type hinting to make your code more robust and maintainable. These concepts will help you write cleaner and more efficient PHP code. 65 | 66 | 67 | 68 | // Here are 10 real-world examples of functions in PHP: 69 | 70 | // ✅User Authentication Function: 71 | // A function to check if a user's credentials are valid. 72 | 73 | // function authenticateUser($username, $password) { 74 | // // Check username and password in the database 75 | // // Return true if valid, false otherwise 76 | // } 77 | 78 | 79 | // ✅Email Sending Function: 80 | // A function to send emails with proper error handling. 81 | 82 | // function sendEmail($to, $subject, $message) { 83 | // // Code to send email using a library like PHPMailer or SwiftMailer 84 | // } 85 | 86 | 87 | //✅ Database Connection Function: 88 | // A function to establish a database connection. 89 | 90 | // function connectToDatabase() { 91 | // $connection = mysqli_connect("host", "user", "password", "database"); 92 | // return $connection; 93 | // } 94 | 95 | 96 | //✅ File Upload Function: 97 | // A function to handle file uploads and validations. 98 | 99 | // function uploadFile($file) { 100 | // // Handle file upload and validation 101 | // // Return true on success, false on failure 102 | // } 103 | 104 | 105 | // Currency Conversion Function: 106 | // A function to convert currency using an API. 107 | 108 | // function convertCurrency($amount, $fromCurrency, $toCurrency) { 109 | // // Use a currency conversion API to convert amounts 110 | // // Return the converted amount 111 | // } 112 | 113 | 114 | // ✅Logging Function: 115 | // A function to log errors or events to a file. 116 | 117 | // function logEvent($message) { 118 | // $logFile = fopen("error.log", "a"); 119 | // fwrite($logFile, date("Y-m-d H:i:s") . " - " . $message . "\n"); 120 | // fclose($logFile); 121 | // } 122 | 123 | 124 | //✅ Image Resizing Function: 125 | // A function to resize and save images. 126 | 127 | // function resizeImage($sourceFile, $targetFile, $width, $height) { 128 | // // Resize the image and save it to the target file 129 | // } 130 | 131 | 132 | // ✅Data Validation Function: 133 | // A function to validate user input data. 134 | 135 | // function validateData($data) { 136 | // // Perform data validation checks 137 | // // Return true if data is valid, false otherwise 138 | // } 139 | 140 | 141 | // ✅HTTP Request Function: 142 | // A function to make HTTP requests to external APIs. 143 | 144 | // function makeHttpRequest($url, $method = 'GET', $data = null) { 145 | // // Make HTTP requests using cURL or other libraries 146 | // // Return the response 147 | // } 148 | 149 | 150 | // ✅Shopping Cart Function: 151 | // A function to manage a user's shopping cart in an e-commerce website. 152 | 153 | // function addToCart($product, $quantity) { 154 | // // Add products to the user's shopping cart 155 | // } 156 | 157 | 158 | // These examples demonstrate how functions can be used to encapsulate and reuse code for various tasks in real-world PHP applications. Functions make your code more modular, readable, and maintainable. -------------------------------------------------------------------------------- /module2/7_function_advance.js: -------------------------------------------------------------------------------- 1 | // ✅Variadic Functions: 2 | // Variadic functions in PHP allow you to accept an arbitrary number of arguments in a function. You can use the func_get_args() function or the ... (splat) operator to work with these arguments. Here's an example: 3 | 4 | 5 | // function sum(...$numbers) { 6 | // $result = 0; 7 | // foreach ($numbers as $number) { 8 | // $result += $number; 9 | // } 10 | // return $result; 11 | // } 12 | 13 | // echo sum(1, 2, 3, 4, 5); // Outputs: 15 14 | 15 | 16 | // In this example, the sum function can accept any number of arguments and returns their sum. 17 | 18 | // ✅Decomposing Large Functions: 19 | // Breaking down large functions into smaller, more manageable functions is a crucial software engineering practice. It improves code readability, maintainability, and reusability. Here's an example: 20 | 21 | 22 | // function processOrder($order) { 23 | // // Complex logic for processing an order 24 | // // ... 25 | // // ... 26 | // sendConfirmationEmail($order); 27 | // updateInventory($order); 28 | // } 29 | 30 | // function sendConfirmationEmail($order) { 31 | // // Logic to send an email confirmation 32 | // // ... 33 | // } 34 | 35 | // function updateInventory($order) { 36 | // // Logic to update inventory 37 | // // ... 38 | // } 39 | 40 | // In this example, we've decomposed the processOrder function into smaller functions, making the code more organized and easier to understand. 41 | 42 | // ✅Recursive Functions: 43 | // Recursive functions are functions that call themselves. They are commonly used to solve problems that can be broken down into smaller, similar subproblems. Let's use the example of printing the Fibonacci series using recursion: 44 | 45 | 46 | // function fibonacci($n) { 47 | // if ($n <= 0) { 48 | // return 0; 49 | // } elseif ($n == 1) { 50 | // return 1; 51 | // } else { 52 | // return fibonacci($n - 1) + fibonacci($n - 2); 53 | // } 54 | // } 55 | 56 | // $terms = 10; 57 | // for ($i = 0; $i < $terms; $i++) { 58 | // echo fibonacci($i) . " "; 59 | // } 60 | // // Outputs: 0 1 1 2 3 5 8 13 21 34 61 | // In this example, the fibonacci function calculates the nth Fibonacci number using recursion. 62 | 63 | 64 | 65 | // 👇Benefits of Breaking Down Large Functions: 66 | // Readability: Smaller functions are easier to read and understand, making your code more maintainable. 67 | 68 | // Reusability: You can reuse smaller functions in different parts of your code. 69 | 70 | // Testing: Smaller functions are easier to test individually, which leads to more reliable code. 71 | 72 | // Collaboration: Smaller functions make it easier for multiple developers to work on different parts of the codebase simultaneously. 73 | 74 | // Debugging: When issues arise, it's easier to pinpoint problems in smaller functions. 75 | 76 | // 👇Strategies for Breaking Down Complex Functions: 77 | // Single Responsibility Principle (SRP): Each function should have a single responsibility or perform a single task. 78 | 79 | // Parameters and Return Values: Use parameters to pass data into functions and return values to get data out of them. 80 | 81 | // Avoid Deep Nesting: Reduce code nesting to improve readability. 82 | 83 | // Comments and Documentation: Document each function's purpose and usage. 84 | 85 | // Modularity: Organize related functions into classes or namespaces. 86 | 87 | // I hope this helps you understand these PHP concepts better. If you have any specific questions or need further clarification, feel free to ask! -------------------------------------------------------------------------------- /module2/8_scope.js: -------------------------------------------------------------------------------- 1 | // 👉Let's dive into the concepts of variable scope in PHP, including local vs. global variable scope, the global keyword, and the static keyword. I'll provide code examples to illustrate each concept. 2 | 3 | // 1.✅ Local vs. Global Variable Scope: 4 | // In PHP, variables can have different scopes, which determine where in your code they can be accessed. 5 | 6 | // ✅Local Variables: Variables declared inside a function are considered local to that function. They can only be accessed within that function. 7 | 8 | 9 | // function localScopeExample() { 10 | // $localVar = 10; 11 | // echo $localVar; 12 | // } 13 | 14 | // localScopeExample(); // Outputs: 10 15 | 16 | // echo $localVar; // This will result in an error, as $localVar is not accessible outside the function. 17 | 18 | 19 | // ✅Global Variables: Variables declared outside of any function or in the global scope are considered global variables. They can be accessed from anywhere in your code. 20 | 21 | 22 | // $globalVar = 20; 23 | 24 | // function accessGlobalVar() { 25 | // global $globalVar; 26 | // echo $globalVar; 27 | // } 28 | 29 | // accessGlobalVar(); // Outputs: 20 30 | // echo $globalVar; // Outputs: 20 31 | 32 | 33 | // 2.✅ Understanding the global Keyword: 34 | // The global keyword is used inside a function to access global variables within that function. 35 | 36 | 37 | // $globalVar = 30; 38 | 39 | // function accessGlobalVarWithGlobalKeyword() { 40 | // global $globalVar; 41 | // echo $globalVar; 42 | // } 43 | 44 | // accessGlobalVarWithGlobalKeyword(); // Outputs: 30 45 | 46 | // 3. ✅The static Keyword: Usage and Implications: 47 | // The static keyword is used to create static variables within a function. Static variables retain their values between function calls. 48 | 49 | 50 | // function staticVariableExample() { 51 | // static $counter = 0; 52 | // $counter++; 53 | // echo $counter; 54 | // } 55 | 56 | // staticVariableExample(); // Outputs: 1 57 | // staticVariableExample(); // Outputs: 2 58 | // staticVariableExample(); // Outputs: 3 59 | 60 | // Static variables are initialized only once when the function is first called, and their values persist across subsequent calls to the same function. 61 | 62 | 63 | // function persistentStaticVariable() { 64 | // static $counter = 0; 65 | // $counter++; 66 | // echo $counter; 67 | // } 68 | 69 | // persistentStaticVariable(); // Outputs: 1 70 | // persistentStaticVariable(); // Outputs: 2 71 | // // The $counter variable retains its value between function calls. 72 | // persistentStaticVariable(); // Outputs: 3 73 | 74 | // These are the fundamental concepts of variable scope in PHP, along with the usage of the global and static keywords. Understanding these concepts is essential for effective PHP programming, as it helps you manage and control the visibility and lifetime of your variables within your code. -------------------------------------------------------------------------------- /module2/9_multiplication_table.js: -------------------------------------------------------------------------------- 1 | // Below is a comprehensive PHP script that demonstrates the use of loops (for loop) and functions in PHP. This script generates a multiplication table for a given number using a custom function and a for loop. 2 | 3 | 4 | // 24 | 25 | 26 | 27 | // In this script: 28 | 29 | // We define a function called generateMultiplicationTable that takes two parameters: $number (the number for which we want to generate the multiplication table) and $limit (the limit for the multiplication table). 30 | 31 | // Inside the function, we use a for loop to iterate from 1 to $limit. For each iteration, we calculate the product of $number and the current value of $i and display the result in the format "number x i = result". 32 | 33 | // We define a variable $multiplier to specify the number for which we want to generate the multiplication table, and a variable $tableLimit to specify how many times we want to multiply. 34 | 35 | // Finally, we call the generateMultiplicationTable function with the chosen $multiplier and $tableLimit to display the multiplication table. 36 | 37 | // You can customize the $multiplier and $tableLimit variables to generate multiplication tables for different numbers and limits. This script demonstrates the use of functions and loops in PHP to create a reusable and organized piece of code. -------------------------------------------------------------------------------- /module3/1_array_basic.php: -------------------------------------------------------------------------------- 1 | 'Alice', 32 | // 'age' => 22, 33 | // 'grade' => 'A' 34 | // ]; 35 | // echo $student['name']; // Output: Alice 36 | 37 | 38 | // ✅Multidimensional Arrays: 39 | // Multidimensional arrays are arrays of arrays. They allow you to create complex data structures by nesting arrays within arrays. 40 | 41 | 42 | // $matrix = [ 43 | // [1, 2, 3], 44 | // [4, 5, 6], 45 | // [7, 8, 9] 46 | // ]; 47 | 48 | // echo $matrix[1][2]; // Output: 6 (accessing the element in the second row and third column) 49 | 50 | 51 | // 3. ✅Array Declaration and Initialization: 52 | // Arrays can be declared and initialized using several methods, including square brackets [] and the array() function. 53 | 54 | 55 | // ✅Using square brackets (modern syntax) 56 | // $colors = ['red', 'green', 'blue']; 57 | 58 | // ✅Using the array() function (older syntax) 59 | // $fruits = array('apple', 'banana', 'cherry'); 60 | 61 | // 4. ✅Accessing Elements in an Array: 62 | // To access elements in an array, use the array name followed by the index (for numeric arrays) or the key (for associative arrays) enclosed in square brackets. 63 | 64 | 65 | // $colors = ['red', 'green', 'blue']; 66 | // echo $colors[1]; // Output: green 67 | 68 | // $student = ['name' => 'Alice', 'age' => 22]; 69 | // echo $student['age']; // Output: 22 70 | 71 | 72 | // 5. Adding and Removing Elements: 73 | // You can add elements to an array using the array assignment operator [] or the array_push() function. To remove elements, you can use the unset() function. 74 | 75 | 76 | // ✅Adding elements 77 | // $fruits = ['apple', 'banana', 'cherry']; 78 | // $fruits[] = 'orange'; // Adds 'orange' to the end of the array 79 | // array_push($fruits, 'grape'); // Adds 'grape' to the end of the array 80 | 81 | // ✅Removing elements 82 | // unset($fruits[1]); // Removes the element at index 1 ('banana') 83 | 84 | // 6. Modifying Array Elements and Resizing Arrays: 85 | // You can modify array elements by assigning new values to specific indices or keys. To resize an array, you can use functions like array_shift() and array_pop() for numeric arrays and array_splice() for associative arrays. 86 | 87 | 88 | // ✅Modifying array elements 89 | // $fruits = ['apple', 'banana', 'cherry']; 90 | // $fruits[1] = 'kiwi'; // Modifies 'banana' to 'kiwi' 91 | 92 | // ✅Resizing numeric arrays 93 | // array_shift($fruits); // Removes the first element ('apple') 94 | // array_pop($fruits); // Removes the last element ('cherry') 95 | 96 | // ✅Resizing associative arrays 97 | // $student = ['name' => 'Alice', 'age' => 22, 'grade' => 'A']; 98 | // unset($student['grade']); // Removes the 'grade' element 99 | 100 | // These concepts provide a solid foundation for working with arrays in PHP. Arrays are a fundamental part of PHP programming and are used extensively in various applications, from simple data storage to complex data manipulation. 101 | 102 | 103 | 104 | 105 | 106 | 107 | // 1.✅ Initializing and Displaying Numeric Array: 108 | 109 | // $numbers = [10, 20, 30, 40, 50]; 110 | 111 | // Displaying array elements using a loop 112 | // foreach ($numbers as $number) { 113 | // echo $number . " "; 114 | // } 115 | // Output: 10 20 30 40 50 116 | 117 | // 2. ✅Associative Array with Key-Value Pairs: 118 | 119 | // $student = [ 120 | // 'name' => 'Alice', 121 | // 'age' => 22, 122 | // 'major' => 'Computer Science' 123 | // ]; 124 | 125 | // echo "Student Name: " . $student['name']; 126 | // Output: Student Name: Alice 127 | 128 | // 3. ✅Multidimensional Array for a Simple Table: 129 | 130 | // $products = [ 131 | // ['ProductID' => 1, 'Name' => 'Laptop', 'Price' => 800], 132 | // ['ProductID' => 2, 'Name' => 'Smartphone', 'Price' => 400], 133 | // ['ProductID' => 3, 'Name' => 'Tablet', 'Price' => 300] 134 | // ]; 135 | 136 | // echo $products[1]['Name']; // Output: Smartphone 137 | 138 | // 4. ✅Adding Elements to an Array: 139 | 140 | // $fruits = ['apple', 'banana', 'cherry']; 141 | 142 | // Adding elements to the end of the array 143 | // $fruits[] = 'orange'; 144 | // $fruits[] = 'grape'; 145 | 146 | // Displaying the updated array 147 | // print_r($fruits); 148 | /* Output: 149 | Array 150 | ( 151 | [0] => apple 152 | [1] => banana 153 | [2] => cherry 154 | [3] => orange 155 | [4] => grape 156 | ) 157 | */ 158 | 159 | 160 | // 5.✅ Removing Elements from an Array: 161 | 162 | // $colors = ['red', 'green', 'blue']; 163 | 164 | // Removing the first element ('red') 165 | // array_shift($colors); 166 | 167 | // Removing the last element ('blue') 168 | // array_pop($colors); 169 | 170 | // Displaying the updated array 171 | // print_r($colors); 172 | /* Output: 173 | Array 174 | ( 175 | [0] => green 176 | ) 177 | */ 178 | 179 | // 6. ✅Modifying Array Elements: 180 | 181 | // $animals = ['cat', 'dog', 'elephant']; 182 | 183 | // Modifying the second element 184 | // $animals[1] = 'horse'; 185 | 186 | // Displaying the updated array 187 | // print_r($animals); 188 | /* Output: 189 | Array 190 | ( 191 | [0] => cat 192 | [1] => horse 193 | [2] => elephant 194 | ) 195 | */ 196 | 197 | 198 | // 7.✅ Resizing an Associative Array: 199 | 200 | // $person = [ 201 | // 'name' => 'John', 202 | // 'age' => 30, 203 | // 'email' => 'john@example.com' 204 | // ]; 205 | 206 | // Removing the 'email' key 207 | // unset($person['email']); 208 | 209 | // Displaying the updated associative array 210 | // print_r($person); 211 | /* Output: 212 | Array 213 | ( 214 | [name] => John 215 | [age] => 30 216 | ) 217 | */ 218 | 219 | 220 | // 8.✅ Using array_slice() to Extract a Subset: 221 | 222 | // $months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']; 223 | 224 | // Extracting the first three months 225 | // $quarter = array_slice($months, 0, 3); 226 | 227 | // Displaying the extracted array 228 | // print_r($quarter); 229 | /* Output: 230 | Array 231 | ( 232 | [0] => Jan 233 | [1] => Feb 234 | [2] => Mar 235 | ) 236 | */ 237 | 238 | // 9.✅ Merging Two Arrays: 239 | 240 | // $fruits1 = ['apple', 'banana']; 241 | // $fruits2 = ['cherry', 'orange']; 242 | 243 | // Merging two arrays 244 | // $combinedFruits = array_merge($fruits1, $fruits2); 245 | 246 | // Displaying the merged array 247 | // print_r($combinedFruits); 248 | /* Output: 249 | Array 250 | ( 251 | [0] => apple 252 | [1] => banana 253 | [2] => cherry 254 | [3] => orange 255 | ) 256 | */ 257 | 258 | 259 | // 10.✅ Sorting an Associative Array by Values: 260 | 261 | // $ages = [ 262 | // 'Alice' => 25, 263 | // 'Bob' => 30, 264 | // 'Charlie' => 20 265 | // ]; 266 | 267 | // Sorting by values in ascending order 268 | // asort($ages); 269 | 270 | // Displaying the sorted array 271 | // print_r($ages); 272 | /* Output: 273 | Array 274 | ( 275 | [Charlie] => 20 276 | [Alice] => 25 277 | [Bob] => 30 278 | ) 279 | */ 280 | 281 | 282 | 283 | // Challenge 1: Numeric Array Average 284 | // Create a PHP function that takes a numeric array as input and returns the average (mean) of its elements. 285 | 286 | // Challenge 2: Array Search 287 | // Write a PHP script that searches for a specific element in an array and returns its index if found, or a message if not found. 288 | 289 | // Challenge 3: Associative Array Sort 290 | // Build a PHP function that sorts an associative array of student names and their respective grades in descending order of grades. Output the sorted array. 291 | 292 | // Challenge 4: Shopping Cart 293 | // Create a PHP shopping cart using an array to store products (associative arrays with name and price). Implement functionality to add, remove, and display items in the cart. 294 | 295 | // Challenge 5: Matrix Multiplication 296 | // Write a PHP script that performs matrix multiplication for two given multidimensional arrays and outputs the result. 297 | 298 | // Challenge 6: Palindrome Checker 299 | // Build a PHP function that checks whether a given string is a palindrome (reads the same backward as forward) and returns true or false. 300 | 301 | // Challenge 7: Unique Values 302 | // Create a PHP function that takes an array of numbers and returns a new array containing only the unique values (removing duplicates). 303 | 304 | // Challenge 8: Merge Arrays 305 | // Write a PHP function that takes two numeric arrays as input and merges them into a single array, removing any duplicates. 306 | 307 | // Challenge 9: Word Frequency Counter 308 | // Develop a PHP script that takes a paragraph of text and generates an associative array where keys are unique words, and values are the frequency of each word in the text. 309 | 310 | // Challenge 10: Tic-Tac-Toe Game 311 | // Create a PHP implementation of the Tic-Tac-Toe game. Use a multidimensional array to represent the game board and implement the game logic, including checking for a win or a draw. 312 | 313 | // These challenges cover a range of real-world scenarios where PHP arrays and their manipulation are commonly used. They are designed to reinforce your understanding and provide practical coding experience. 314 | 315 | 316 | // Here are the solutions to the 10 real-world coding challenges based on PHP arrays: 317 | 318 | // ✅Challenge 1: Numeric Array Average 319 | 320 | 321 | // function calculateAverage($numbers) { 322 | // $sum = array_sum($numbers); 323 | // $count = count($numbers); 324 | // return $count > 0 ? $sum / $count : 0; 325 | // } 326 | 327 | // $numericArray = [10, 20, 30, 40, 50]; 328 | // $average = calculateAverage($numericArray); 329 | // echo "Average: $average"; 330 | 331 | 332 | 333 | // ✅Challenge 2: Array Search 334 | 335 | 336 | // function findElementIndex($array, $element) { 337 | // $index = array_search($element, $array); 338 | // return $index !== false ? $index : "Element not found"; 339 | // } 340 | 341 | // $fruits = ['apple', 'banana', 'cherry']; 342 | // $searchElement = 'banana'; 343 | // $result = findElementIndex($fruits, $searchElement); 344 | // echo "Index of $searchElement: $result"; 345 | 346 | 347 | // ✅Challenge 3: Associative Array Sort 348 | 349 | 350 | // $students = [ 351 | // 'Alice' => 85, 352 | // 'Bob' => 92, 353 | // 'Charlie' => 78 354 | // ]; 355 | 356 | // arsort($students); 357 | // print_r($students); 358 | 359 | 360 | // ✅Challenge 4: Shopping Cart 361 | 362 | 363 | // $cart = []; 364 | 365 | // // Add items to the cart 366 | // function addToCart($cart, $product, $price) { 367 | // $cart[] = ['product' => $product, 'price' => $price]; 368 | // return $cart; 369 | // } 370 | 371 | // $cart = addToCart($cart, 'Laptop', 800); 372 | // $cart = addToCart($cart, 'Smartphone', 400); 373 | 374 | // // Remove an item from the cart 375 | // function removeFromCart($cart, $index) { 376 | // if (isset($cart[$index])) { 377 | // unset($cart[$index]); 378 | // return array_values($cart); // Reindex the array 379 | // } 380 | // return $cart; 381 | // } 382 | 383 | // $cart = removeFromCart($cart, 0); 384 | 385 | // // Display items in the cart 386 | // foreach ($cart as $item) { 387 | // echo $item['product'] . ': $' . $item['price'] . '
'; 388 | // } 389 | 390 | 391 | //✅ Challenge 5: Matrix Multiplication 392 | 393 | 394 | // function matrixMultiply($matrix1, $matrix2) { 395 | // $result = []; 396 | // foreach ($matrix1 as $i => $row) { 397 | // foreach ($matrix2[0] as $j => $col) { 398 | // $result[$i][$j] = 0; 399 | // foreach ($row as $k => $val) { 400 | // $result[$i][$j] += $val * $matrix2[$k][$j]; 401 | // } 402 | // } 403 | // } 404 | // return $result; 405 | // } 406 | 407 | // $matrix1 = [[1, 2], [3, 4]]; 408 | // $matrix2 = [[5, 6], [7, 8]]; 409 | 410 | // $resultMatrix = matrixMultiply($matrix1, $matrix2); 411 | // print_r($resultMatrix); 412 | 413 | 414 | // ✅Challenge 6: Palindrome Checker 415 | 416 | 417 | // function isPalindrome($str) { 418 | // $str = str_replace(' ', '', $str); 419 | // $str = strtolower($str); 420 | // return $str === strrev($str); 421 | // } 422 | 423 | // $text = "A man a plan a canal Panama"; 424 | // $isPalindrome = isPalindrome($text); 425 | // echo $isPalindrome ? 'Palindrome' : 'Not a Palindrome'; 426 | 427 | 428 | //✅ Challenge 7: Unique Values 429 | 430 | 431 | // function getUniqueValues($numbers) { 432 | // return array_values(array_unique($numbers)); 433 | // } 434 | 435 | // $numbers = [1, 2, 2, 3, 4, 4, 5]; 436 | // $uniqueValues = getUniqueValues($numbers); 437 | // print_r($uniqueValues); 438 | 439 | 440 | // ✅Challenge 8: Merge Arrays 441 | 442 | 443 | // function mergeArrays($array1, $array2) { 444 | // return array_values(array_unique(array_merge($array1, $array2))); 445 | // } 446 | 447 | // $numbers1 = [1, 2, 3]; 448 | // $numbers2 = [3, 4, 5]; 449 | // $mergedArray = mergeArrays($numbers1, $numbers2); 450 | // print_r($mergedArray); 451 | 452 | 453 | // ✅Challenge 9: Word Frequency Counter 454 | 455 | 456 | // function wordFrequency($text) { 457 | // $words = str_word_count(strtolower($text), 1); 458 | // $wordCount = array_count_values($words); 459 | // arsort($wordCount); 460 | // return $wordCount; 461 | // } 462 | 463 | // $text = "This is a sample text. This text contains words, and it is a sample."; 464 | // $wordFrequency = wordFrequency($text); 465 | // print_r($wordFrequency); 466 | 467 | 468 | -------------------------------------------------------------------------------- /module3/3_array_function.php: -------------------------------------------------------------------------------- 1 | "John", "age" => 25]; 61 | // $hasName = array_key_exists("name", $student); // $hasName is true 62 | 63 | 64 | //✅ in_array(): Checks if a specific value exists in an array. 65 | 66 | // $fruits = ["apple", "banana", "cherry"]; 67 | // $isBanana = in_array("banana", $fruits); // $isBanana is true 68 | 69 | // These are some of the most commonly used array functions in PHP. Mastering them will greatly enhance your ability to work with arrays effectively in PHP. 70 | 71 | 72 | // ✅ Here are 10 real-world code examples that demonstrate the usage of the PHP array functions I mentioned earlier: 73 | 74 | // 1. Using count() to determine the number of items in a shopping cart: 75 | 76 | 77 | // $cart = ["item1", "item2", "item3"]; 78 | // $itemCount = count($cart); 79 | // echo "There are $itemCount items in your cart."; 80 | 81 | // 2. Using array_push() to add a new product to a list of favorites: 82 | 83 | 84 | // $favorites = ["product1", "product2"]; 85 | // $newProduct = "product3"; 86 | // array_push($favorites, $newProduct); 87 | // print_r($favorites); 88 | 89 | // 3.✅ Using array_pop() to remove and display the last error message in a log: 90 | 91 | 92 | // $errorLog = ["Error 1", "Error 2", "Error 3"]; 93 | // $lastError = array_pop($errorLog); 94 | // echo "Last error: $lastError"; 95 | 96 | // 4.✅ Using array_unshift() to add a greeting to a list of messages: 97 | 98 | 99 | // $messages = ["Message 1", "Message 2"]; 100 | // $newMessage = "Hello!"; 101 | // array_unshift($messages, $newMessage); 102 | // print_r($messages); 103 | 104 | // 5.✅ Using array_shift() to display and remove the oldest email in a mailbox: 105 | 106 | 107 | // $mailbox = ["Email 1", "Email 2", "Email 3"]; 108 | // $oldestEmail = array_shift($mailbox); 109 | // echo "You have a new email: $oldestEmail"; 110 | 111 | // 6.✅ Using array_merge() to combine two arrays of user roles: 112 | 113 | 114 | // $rolesAdmin = ["admin", "editor"]; 115 | // $rolesUser = ["user"]; 116 | // $combinedRoles = array_merge($rolesAdmin, $rolesUser); 117 | // print_r($combinedRoles); 118 | 119 | 120 | // 7.✅ Using array_slice() to paginate a list of articles: 121 | 122 | 123 | // $articles = ["Article 1", "Article 2", "Article 3", "Article 4"]; 124 | // $page = 2; 125 | // $perPage = 2; 126 | // $startIndex = ($page - 1) * $perPage; 127 | // $paginatedArticles = array_slice($articles, $startIndex, $perPage); 128 | // print_r($paginatedArticles); 129 | 130 | 131 | // 8.✅ Using array_splice() to replace elements in a list of ingredients: 132 | 133 | 134 | // $ingredients = ["salt", "sugar", "flour"]; 135 | // array_splice($ingredients, 1, 1, "butter"); 136 | // print_r($ingredients); 137 | 138 | 139 | // 9.✅ Using array_filter() to filter out inactive users from a user list: 140 | 141 | 142 | // $users = [ 143 | // ["name" => "Alice", "active" => true], 144 | // ["name" => "Bob", "active" => false], 145 | // ["name" => "Charlie", "active" => true], 146 | // ]; 147 | // $activeUsers = array_filter($users, function ($user) { 148 | // return $user["active"]; 149 | // }); 150 | // print_r($activeUsers); 151 | 152 | // 10.✅ Using array_map() to format a list of dates: 153 | 154 | 155 | // $dates = ["2023-09-01", "2023-09-15", "2023-09-30"]; 156 | // $formattedDates = array_map(function ($date) { 157 | // return date("F j, Y", strtotime($date)); 158 | // }, $dates); 159 | // print_r($formattedDates); 160 | 161 | 162 | // These examples illustrate how you can use these array functions in real-world scenarios to solve various programming challenges. 163 | 164 | 165 | // ✅ Here is a list of 20 commonly used array functions in PHP: 166 | 167 | // count(): Counts the number of elements in an array. 168 | // array_push(): Adds one or more elements to the end of an array. 169 | // array_pop(): Removes and returns the last element of an array. 170 | // array_unshift(): Adds one or more elements to the beginning of an array. 171 | // array_shift(): Removes and returns the first element of an array. 172 | // array_merge(): Merges two or more arrays into one. 173 | // array_slice(): Extracts a portion of an array. 174 | // array_splice(): Adds, removes, or replaces elements in an array. 175 | // array_filter(): Filters elements in an array based on a callback function. 176 | // array_map(): Applies a callback function to all elements of an array. 177 | // array_key_exists(): Checks if a specific key exists in an array. 178 | // in_array(): Checks if a specific value exists in an array. 179 | // array_unique(): Removes duplicate values from an array. 180 | // array_reverse(): Reverses the order of elements in an array. 181 | // array_search(): Searches for a value in an array and returns its key if found. 182 | // sort(): Sorts an array in ascending order. 183 | // rsort(): Sorts an array in descending order. 184 | // asort(): Sorts an associative array in ascending order by its values. 185 | // arsort(): Sorts an associative array in descending order by its values. 186 | // ksort(): Sorts an associative array in ascending order by its keys. 187 | // These array functions are frequently used in PHP to perform various operations on arrays, making them essential for working with data efficiently in PHP applications. 188 | 189 | 190 | // ✅ Here are 10 coding challenges based on the concepts of array manipulation in PHP: 191 | 192 | // 1. Count the Occurrences: 193 | 194 | // Write a function that takes an array and a value as parameters and returns the number of times the value appears in the array. 195 | 196 | // 2. Reverse an Array: 197 | 198 | // Create a function to reverse the elements of an array without using the array_reverse() function. 199 | 200 | // 3. Find the Maximum Value: 201 | 202 | // Write a function that finds and returns the maximum value in an array of numbers. 203 | 204 | // 4. Remove Duplicates: 205 | 206 | // Create a function that removes duplicate values from an array while preserving the original order of elements. 207 | 208 | // 5. Merge Two Arrays: 209 | 210 | // Write a function that takes two arrays as input and merges them into a single sorted array. 211 | 212 | // 6. Implement a Stack: 213 | 214 | // Implement a stack (Last-In-First-Out) using an array. Include push and pop operations. 215 | 216 | // 7. Implement a Queue: 217 | 218 | // Implement a queue (First-In-First-Out) using an array. Include enqueue and dequeue operations. 219 | 220 | // 8. Filter an Associative Array: 221 | 222 | // Given an associative array of products with their prices, write a function that filters out products below a certain price threshold. 223 | 224 | // 9. Group By Category: 225 | 226 | // Given an array of items with category information, create a function that groups the items by their category into a multidimensional array. 227 | 228 | // 10. Search and Replace: 229 | 230 | // Write a function that searches for a specific word in an array of strings and replaces it with a given replacement word. 231 | 232 | // These challenges will test your understanding of array functions in PHP and your ability to use them effectively to solve common programming problems. 233 | 234 | // ✅Here are the solutions to the 10 coding challenges using PHP: 235 | 236 | // 1. Count the Occurrences: 237 | 238 | 239 | // function countOccurrences($array, $value) { 240 | // $count = 0; 241 | // foreach ($array as $element) { 242 | // if ($element == $value) { 243 | // $count++; 244 | // } 245 | // } 246 | // return $count; 247 | // } 248 | 249 | // $numbers = [1, 2, 2, 3, 4, 2]; 250 | // $valueToCount = 2; 251 | // $result = countOccurrences($numbers, $valueToCount); 252 | // echo "The value $valueToCount appears $result times in the array."; 253 | 254 | 255 | // 2. Reverse an Array: 256 | 257 | 258 | // function reverseArray($array) { 259 | // $reversed = []; 260 | // for ($i = count($array) - 1; $i >= 0; $i--) { 261 | // $reversed[] = $array[$i]; 262 | // } 263 | // return $reversed; 264 | // } 265 | 266 | // $originalArray = [1, 2, 3, 4, 5]; 267 | // $reversedArray = reverseArray($originalArray); 268 | // print_r($reversedArray); 269 | 270 | 271 | // 3. Find the Maximum Value: 272 | 273 | 274 | // function findMax($array) { 275 | // $max = $array[0]; 276 | // foreach ($array as $value) { 277 | // if ($value > $max) { 278 | // $max = $value; 279 | // } 280 | // } 281 | // return $max; 282 | // } 283 | 284 | // $numbers = [34, 12, 56, 78, 45]; 285 | // $maxValue = findMax($numbers); 286 | // echo "The maximum value in the array is: $maxValue"; 287 | 288 | 289 | // 4. Remove Duplicates: 290 | 291 | 292 | // function removeDuplicates($array) { 293 | // return array_values(array_unique($array)); 294 | // } 295 | 296 | // $originalArray = [1, 2, 2, 3, 4, 4, 5]; 297 | // $uniqueArray = removeDuplicates($originalArray); 298 | // print_r($uniqueArray); 299 | 300 | 301 | // 5. Merge Two Arrays: 302 | 303 | 304 | // function mergeArrays($array1, $array2) { 305 | // return array_merge($array1, $array2); 306 | // } 307 | 308 | // $array1 = [1, 2, 3]; 309 | // $array2 = [4, 5, 6]; 310 | // $mergedArray = mergeArrays($array1, $array2); 311 | // print_r($mergedArray); 312 | 313 | 314 | // 6. Implement a Stack: 315 | 316 | 317 | // class Stack { 318 | // private $stack; 319 | 320 | // public function __construct() { 321 | // $this->stack = []; 322 | // } 323 | 324 | // public function push($item) { 325 | // array_push($this->stack, $item); 326 | // } 327 | 328 | // public function pop() { 329 | // return array_pop($this->stack); 330 | // } 331 | // } 332 | 333 | // $stack = new Stack(); 334 | // $stack->push(1); 335 | // $stack->push(2); 336 | // $stack->push(3); 337 | // echo $stack->pop(); // Outputs 3 338 | 339 | 340 | // 7. Implement a Queue: 341 | 342 | 343 | // class Queue { 344 | // private $queue; 345 | 346 | // public function __construct() { 347 | // $this->queue = []; 348 | // } 349 | 350 | // public function enqueue($item) { 351 | // array_push($this->queue, $item); 352 | // } 353 | 354 | // public function dequeue() { 355 | // return array_shift($this->queue); 356 | // } 357 | // } 358 | 359 | // $queue = new Queue(); 360 | // $queue->enqueue(1); 361 | // $queue->enqueue(2); 362 | // $queue->enqueue(3); 363 | // echo $queue->dequeue(); // Outputs 1 364 | 365 | 366 | // 8. Filter an Associative Array: 367 | 368 | 369 | // function filterByPrice($products, $threshold) { 370 | // $filteredProducts = []; 371 | // foreach ($products as $product => $price) { 372 | // if ($price >= $threshold) { 373 | // $filteredProducts[$product] = $price; 374 | // } 375 | // } 376 | // return $filteredProducts; 377 | // } 378 | 379 | // $products = [ 380 | // "product1" => 10, 381 | // "product2" => 25, 382 | // "product3" => 5, 383 | // "product4" => 15, 384 | // ]; 385 | 386 | // $filteredProducts = filterByPrice($products, 15); 387 | // print_r($filteredProducts); 388 | 389 | 390 | // 9. Group By Category: 391 | 392 | 393 | // function groupByCategory($items) { 394 | // $groupedItems = []; 395 | // foreach ($items as $item) { 396 | // $category = $item["category"]; 397 | // $groupedItems[$category][] = $item; 398 | // } 399 | // return $groupedItems; 400 | // } 401 | 402 | // $items = [ 403 | // ["name" => "Item 1", "category" => "Category A"], 404 | // ["name" => "Item 2", "category" => "Category B"], 405 | // ["name" => "Item 3", "category" => "Category A"], 406 | // ["name" => "Item 4", "category" => "Category C"], 407 | // ]; 408 | 409 | // $groupedItems = groupByCategory($items); 410 | // print_r($groupedItems); 411 | 412 | 413 | // 10. Search and Replace: 414 | 415 | 416 | // function searchAndReplace($array, $search, $replace) { 417 | // foreach ($array as &$value) { 418 | // if ($value == $search) { 419 | // $value = $replace; 420 | // } 421 | // } 422 | // return $array; 423 | // } 424 | 425 | // $words = ["apple", "banana", "cherry"]; 426 | // $searchWord = "banana"; 427 | // $replacement = "orange"; 428 | // $newWords = searchAndReplace($words, $searchWord, $replacement); 429 | // print_r($newWords); 430 | // These PHP solutions demonstrate how to implement various array manipulation tasks using PHP's array functions and custom functions. 431 | 432 | 433 | 434 | 435 | 436 | -------------------------------------------------------------------------------- /module3/4_handle_string.php: -------------------------------------------------------------------------------- 1 | apple [1] => banana [2] => cherry ) 10 | 11 | 12 | // ✅Converting Array to String (implode): 13 | // The implode (or join) function in PHP joins the elements of an array into a string using a specified glue. 14 | 15 | 16 | // $fruitsArray = ["apple", "banana", "cherry"]; 17 | // $fruitsString = implode(", ", $fruitsArray); 18 | // echo $fruitsString; // Output: apple, banana, cherry 19 | 20 | 21 | // 2. ✅Common Use Cases for String/Array Conversions: 22 | // CSV Data Handling: Converting CSV data (comma-separated values) into arrays for processing and vice versa. 23 | // URL Query Parameters: Parsing URL query parameters (e.g., $_GET data) into an associative array. 24 | // JSON Handling: Converting JSON data to PHP arrays and back. 25 | // Text Parsing: Splitting and manipulating text data for various purposes. 26 | 27 | // 3. ✅Splitting Strings into Arrays Using Multiple Delimiters: 28 | // You can use regular expressions and the preg_split function to split strings using multiple delimiters. 29 | 30 | 31 | // $text = "Hello|World;Goodbye-Planet"; 32 | // $delimiters = "/[|;,-]/"; 33 | // $parts = preg_split($delimiters, $text); 34 | // print_r($parts); // Output: Array ( [0] => Hello [1] => World [2] => Goodbye [3] => Planet ) 35 | 36 | // 4.✅ Examples with CSV, TSV, and Custom Delimiters: 37 | // CSV to Array (Comma-Separated Values): 38 | 39 | // $csvData = "Name,Age,Location\nAlice,25,New York\nBob,30,San Francisco"; 40 | // $dataArray = array_map('str_getcsv', explode("\n", $csvData)); 41 | // print_r($dataArray); 42 | 43 | // ✅TSV to Array (Tab-Separated Values): 44 | 45 | // $tsvData = "Name\tAge\tLocation\nAlice\t25\tNew York\nBob\t30\tSan Francisco"; 46 | // $dataArray = array_map(function($line) { return explode("\t", $line); }, explode("\n", $tsvData)); 47 | // print_r($dataArray); 48 | 49 | // ✅Custom Delimiter (Pipe-Separated Values): 50 | 51 | // $customData = "Name|Age|Location\nAlice|25|New York\nBob|30|San Francisco"; 52 | // $dataArray = array_map(function($line) { return explode("|", $line); }, explode("\n", $customData)); 53 | // print_r($dataArray); 54 | 55 | // 5.✅ Concatenating Strings: 56 | // You can concatenate strings using the . operator or the . assignment operator (.=) to append to an existing string. 57 | 58 | 59 | // $firstName = "John"; 60 | // $lastName = "Doe"; 61 | // $fullName = $firstName . " " . $lastName; 62 | // echo $fullName; // Output: John Doe 63 | 64 | // 6. Trimming and Padding: 65 | // Trimming Whitespace: 66 | // The trim function removes leading and trailing whitespace from a string. 67 | 68 | 69 | // $text = " Hello, World! "; 70 | // $trimmedText = trim($text); 71 | // echo $trimmedText; // Output: Hello, World! 72 | // Padding: 73 | // You can pad a string with spaces or a specific character using str_pad. 74 | 75 | 76 | // $number = "42"; 77 | // $paddedNumber = str_pad($number, 5, "0", STR_PAD_LEFT); 78 | // echo $paddedNumber; // Output: "00042" 79 | 80 | 81 | // 7. Replacing and Formatting Strings: 82 | // Replacing Substrings: 83 | // Use str_replace to replace occurrences of a substring in a string. 84 | 85 | 86 | // $text = "Hello, World!"; 87 | // $newText = str_replace("World", "Universe", $text); 88 | // echo $newText; // Output: Hello, Universe! 89 | 90 | // ✅String Formatting: 91 | // You can format strings using sprintf for precise control over formatting. 92 | 93 | 94 | // $number = 42; 95 | // $formatted = sprintf("The answer is %d.", $number); 96 | // echo $formatted; // Output: The answer is 42. 97 | 98 | // 8. Word Wrapping and Line Breaks: 99 | // Word Wrapping: 100 | // Use wordwrap to break a long string into multiple lines at a specified line length. 101 | 102 | 103 | // $text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; 104 | // $wrappedText = wordwrap($text, 20, "\n"); 105 | // echo $wrappedText; 106 | 107 | // Line Breaks: 108 | // To create HTML line breaks (
) from newline characters, use nl2br. 109 | 110 | 111 | // $text = "Hello\nWorld"; 112 | // $htmlText = nl2br($text); 113 | // echo $htmlText; // Output: Hello
World 114 | 115 | // These PHP concepts and code examples should help you understand and work with string/array conversions, string manipulation, and text formatting effectively in your PHP projects. 116 | 117 | 118 | // ✅Here are 10 PHP code examples to illustrate the concepts of string/array conversions, splitting, concatenating, trimming, padding, replacing, and formatting strings, and word wrapping: 119 | 120 | // 1.✅ CSV Data Conversion: 121 | // Convert CSV data into an array. 122 | 123 | 124 | // $csvData = "Name,Age,Location\nAlice,25,New York\nBob,30,San Francisco"; 125 | // $dataArray = array_map('str_getcsv', explode("\n", $csvData)); 126 | // print_r($dataArray); 127 | 128 | // 2. JSON Data Conversion: 129 | // Convert JSON data into an associative array. 130 | 131 | 132 | // $jsonData = '{"name": "John", "age": 30, "city": "New York"}'; 133 | // $dataArray = json_decode($jsonData, true); 134 | // print_r($dataArray); 135 | 136 | 137 | // 3. Splitting String with Multiple Delimiters: 138 | // Split a string using multiple delimiters (,, ;, and -). 139 | 140 | 141 | // $text = "Hello|World;Goodbye-Planet"; 142 | // $delimiters = "/[|;,-]/"; 143 | // $parts = preg_split($delimiters, $text); 144 | // print_r($parts); 145 | 146 | // 4. String Concatenation: 147 | // Concatenate strings using the . operator. 148 | 149 | 150 | // $firstName = "John"; 151 | // $lastName = "Doe"; 152 | // $fullName = $firstName . " " . $lastName; 153 | // echo $fullName; 154 | 155 | // 5. ✅Trimming Whitespace: 156 | // Trim leading and trailing whitespace from a string. 157 | 158 | 159 | // $text = " Hello, World! "; 160 | // $trimmedText = trim($text); 161 | // echo $trimmedText; 162 | 163 | // 6.✅ Padding with Zeros: 164 | // Pad a number with leading zeros to ensure a fixed length. 165 | 166 | 167 | // $number = "42"; 168 | // $paddedNumber = str_pad($number, 5, "0", STR_PAD_LEFT); 169 | // echo $paddedNumber; 170 | 171 | // 7. String Replacement: 172 | // Replace occurrences of a substring in a string. 173 | 174 | 175 | // $text = "Hello, World!"; 176 | // $newText = str_replace("World", "Universe", $text); 177 | // echo $newText; 178 | 179 | // 8.✅ String Formatting: 180 | // Format strings using sprintf. 181 | 182 | 183 | // $number = 42; 184 | // $formatted = sprintf("The answer is %d.", $number); 185 | // echo $formatted; 186 | 187 | // 9.✅ Word Wrapping: 188 | // Wrap a long string into multiple lines at a specified length. 189 | 190 | 191 | // $text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; 192 | // $wrappedText = wordwrap($text, 20, "\n"); 193 | // echo $wrappedText; 194 | 195 | // 10.✅ Line Breaks in HTML: 196 | // Convert newline characters to HTML line breaks. 197 | 198 | 199 | // $text = "Hello\nWorld"; 200 | // $htmlText = nl2br($text); 201 | // echo $htmlText; 202 | 203 | // These code examples demonstrate various scenarios where these string and array manipulation techniques are useful in PHP programming. 204 | 205 | // ✅Here are 10 coding challenges based on the concepts of string/array conversions, splitting, concatenating, trimming, padding, replacing, and formatting strings, and word wrapping in PHP: 206 | 207 | // 1. CSV to JSON Converter: 208 | // Create a PHP script that reads CSV data and converts it into JSON format. 209 | 210 | // 2. JSON to CSV Converter: 211 | // Develop a PHP program that reads JSON data and converts it into CSV format. 212 | 213 | // 3. String Splitter: 214 | // Write a function that takes a string and a delimiter as input and splits the string into an array using the provided delimiter. 215 | 216 | // 4. Text Formatter: 217 | // Create a program that reads a long text and formats it into paragraphs with a specified maximum line length. Ensure that words are not split. 218 | 219 | // 5. String Replacer: 220 | // Build a PHP function that takes a string, a search term, and a replacement term as input and replaces all occurrences of the search term with the replacement term. 221 | 222 | // 6. String Concatenation with Padding: 223 | // Write a program that takes an array of strings and concatenates them into a single string, separated by a space, while ensuring each element is padded with a fixed number of characters (e.g., 10 characters). 224 | 225 | // 7. HTML Line Break Generator: 226 | // Create a function that takes a text input and converts newline characters into HTML line breaks (
) for displaying text in HTML. 227 | 228 | // 8. String Truncation: 229 | // Write a PHP function that takes a string and a maximum length as input and truncates the string if it exceeds the specified length, adding "..." to indicate truncation. 230 | 231 | // 9. CSV Validator: 232 | // Develop a PHP program that reads CSV data and checks if it is well-formed, ensuring that all rows have the same number of columns. 233 | 234 | // 10. Password Generator: 235 | // Create a function that generates random passwords of a specified length with a mix of characters (letters, numbers, and symbols). The generated passwords should be stored in an array. 236 | 237 | // These coding challenges will help you practice and apply the string and array manipulation concepts you've learned, making you more proficient in using these techniques in real-world PHP applications. 238 | 239 | 240 | // ✅Here are the solutions for the 10 coding challenges based on the concepts of string/array conversions, splitting, concatenating, trimming, padding, replacing, and formatting strings, and word wrapping in PHP: 241 | 242 | // 1. ✅CSV to JSON Converter: 243 | 244 | 245 | // $csvData = "Name,Age,Location\nAlice,25,New York\nBob,30,San Francisco"; 246 | // $dataArray = array_map('str_getcsv', explode("\n", $csvData)); 247 | // $jsonData = json_encode($dataArray, JSON_PRETTY_PRINT); 248 | // echo $jsonData; 249 | // 2. JSON to CSV Converter: 250 | 251 | 252 | // $jsonData = '[{"Name": "Alice", "Age": 25, "Location": "New York"}, {"Name": "Bob", "Age": 30, "Location": "San Francisco"}]'; 253 | // $dataArray = json_decode($jsonData, true); 254 | // $csvData = implode("\n", array_map('str_getcsv', $dataArray)); 255 | // echo $csvData; 256 | 257 | // 3.✅ String Splitter: 258 | 259 | 260 | // function splitString($inputString, $delimiter) { 261 | // return explode($delimiter, $inputString); 262 | // } 263 | 264 | // $string = "Hello|World;Goodbye-Planet"; 265 | // $delimiter = "|"; 266 | // $parts = splitString($string, $delimiter); 267 | // print_r($parts); 268 | 269 | // 4.✅ Text Formatter: 270 | 271 | 272 | // function formatText($inputText, $lineLength) { 273 | // return wordwrap($inputText, $lineLength, "\n", true); 274 | // } 275 | 276 | // $text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; 277 | // $maxLineLength = 20; 278 | // $formattedText = formatText($text, $maxLineLength); 279 | // echo $formattedText; 280 | 281 | // 5.✅ String Replacer: 282 | 283 | 284 | // function replaceString($inputString, $searchTerm, $replaceTerm) { 285 | // return str_replace($searchTerm, $replaceTerm, $inputString); 286 | // } 287 | 288 | // $string = "Hello, World!"; 289 | // $search = "World"; 290 | // $replace = "Universe"; 291 | // $newString = replaceString($string, $search, $replace); 292 | // echo $newString; 293 | 294 | // 6. String Concatenation with Padding: 295 | 296 | 297 | // function concatenateWithPadding($stringArray, $paddingLength) { 298 | // return implode(str_repeat(' ', $paddingLength), $stringArray); 299 | // } 300 | 301 | // $strings = ["Apple", "Banana", "Cherry"]; 302 | // $padding = 5; 303 | // $result = concatenateWithPadding($strings, $padding); 304 | // echo $result; 305 | // 7. ✅HTML Line Break Generator: 306 | 307 | 308 | // function convertToHtmlLineBreaks($inputText) { 309 | // return nl2br($inputText); 310 | // } 311 | 312 | // $text = "Hello\nWorld"; 313 | // $htmlText = convertToHtmlLineBreaks($text); 314 | // echo $htmlText; 315 | 316 | // 8. String Truncation: 317 | 318 | 319 | // function truncateString($inputString, $maxLength) { 320 | // if (strlen($inputString) > $maxLength) { 321 | // return substr($inputString, 0, $maxLength) . "..."; 322 | // } 323 | // return $inputString; 324 | // } 325 | 326 | // $text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; 327 | // $maxLength = 20; 328 | // $truncatedText = truncateString($text, $maxLength); 329 | // echo $truncatedText; 330 | 331 | // 9. CSV Validator: 332 | 333 | 334 | // function isCsvWellFormed($csvData) { 335 | // $rows = explode("\n", $csvData); 336 | // $numColumns = count(str_getcsv($rows[0])); 337 | 338 | // foreach ($rows as $row) { 339 | // $columns = str_getcsv($row); 340 | // if (count($columns) !== $numColumns) { 341 | // return false; 342 | // } 343 | // } 344 | // return true; 345 | // } 346 | 347 | // $csvData = "Name,Age,Location\nAlice,25,New York\nBob,30,San Francisco"; 348 | // $isWellFormed = isCsvWellFormed($csvData); 349 | // echo $isWellFormed ? 'CSV is well-formed' : 'CSV is not well-formed'; 350 | 351 | // 10. Password Generator: 352 | 353 | 354 | // function generatePassword($length) { 355 | // $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+'; 356 | // $password = ''; 357 | 358 | // for ($i = 0; $i < $length; $i++) { 359 | // $password .= $characters[rand(0, strlen($characters) - 1)]; 360 | // } 361 | 362 | // return $password; 363 | // } 364 | 365 | // $passwords = []; 366 | // for ($i = 0; $i < 5; $i++) { 367 | // $passwords[] = generatePassword(10); 368 | // } 369 | 370 | // print_r($passwords); 371 | 372 | // These solutions demonstrate how to implement the given coding challenges related to string/array conversions, string manipulation, and text formatting in PHP. 373 | 374 | 375 | 376 | 377 | 378 | -------------------------------------------------------------------------------- /module3/main.php: -------------------------------------------------------------------------------- 1 | 'Alice', 29 | // 'age' => 22, 30 | // 'grade' => 'A' 31 | // ]; 32 | // echo $student['age']; 33 | 34 | 35 | // ✅Multidimensional Arrays: 36 | 37 | // $matrix = [ 38 | // [1, 2, 3], 39 | // [4, 5, 6], 40 | // [7, 8, 9] 41 | // ]; 42 | 43 | // echo $matrix[0][2]; 44 | 45 | 46 | // ✅Adding elements 47 | // $fruits = ['apple', 'banana', 'cherry']; 48 | // $fruits[] = 'orange'; 49 | // array_push($fruits, 'grape'); 50 | // print_r($fruits); 51 | 52 | // ✅Removing elements 53 | 54 | // unset($fruits[1]); 55 | // print_r($fruits); 56 | 57 | 58 | // ✅Modifying array elements 59 | // $fruits = ['apple', 'banana', 'cherry']; 60 | // $fruits[2] = 'mango'; 61 | // print_r($fruits); 62 | 63 | // ✅Resizing numeric arrays 64 | 65 | // $fruits = ['apple', 'banana', 'cherry']; 66 | // array_shift($fruits); 67 | // array_pop($fruits); 68 | // print_r($fruits); 69 | 70 | // ✅Resizing associative arrays 71 | // $student = ['name' => 'Alice', 'age' => 22, 'grade' => 'A']; 72 | // unset($student['grade']); 73 | // print_r($student); 74 | 75 | 76 | //✅ Associative Array Functions: 77 | 78 | // $student = [ 79 | // 'name' => 'Alice', 80 | // 'age' => 22, 81 | // 'grade' => 'A' 82 | // ]; 83 | 84 | // if (array_key_exists('grade', $student)) { 85 | // echo "Age: " . $student['grade']; 86 | // } 87 | 88 | //✅ Get an array of keys 89 | 90 | // $keys = array_keys($student); 91 | // print_r($keys); 92 | 93 | //✅ Get an array of values 94 | // $values = array_values($student); 95 | // print_r($values); 96 | 97 | 98 | // ✅Creating and Working with Nested Arrays: 99 | 100 | 101 | // $student = [ 102 | // 'name' => 'Alice', 103 | // 'contact' => [ 104 | // 'email' => 'alice@example.com', 105 | // 'phone' => '123-456-7890' 106 | // ] 107 | // ]; 108 | 109 | // echo "Student Email: " . $student['contact']['phone']; 110 | 111 | 112 | // ✅Displaying array elements using a loop 113 | 114 | // $numbers = [10, 20, 30, 40, 50]; 115 | 116 | // foreach ($numbers as $number) { 117 | // echo $number . " "; 118 | // } 119 | 120 | // ✅Merging two arrays 121 | 122 | // $fruits1 = ['apple', 'banana']; 123 | // $fruits2 = ['cherry', 'orange']; 124 | 125 | // $combinedFruits = array_merge($fruits1, $fruits2); 126 | 127 | // print_r($combinedFruits); 128 | 129 | 130 | 131 | // ✅Use the sort() function to sort in ascending order 132 | 133 | // $numbers = array(5, 2, 9, 1, 5, 6); 134 | 135 | // sort($numbers); 136 | 137 | // print_r($numbers); 138 | 139 | 140 | 141 | // ✅Use the rsort() function to sort in descending order 142 | 143 | // $numbers = array(5, 2, 9, 1, 5, 6); 144 | 145 | // rsort($numbers); 146 | 147 | 148 | // print_r($numbers); 149 | 150 | 151 | //✅ Use the asort() function to sort by values in ascending order 152 | 153 | // $fruits = array( 154 | // 'apple' => 5, 155 | // 'banana' => 2, 156 | // 'cherry' => 9, 157 | // 'date' => 1 158 | // ); 159 | 160 | // asort($fruits); 161 | 162 | 163 | // print_r($fruits); 164 | 165 | 166 | 167 | //✅ Use the ksort() function to sort by keys in ascending order 168 | 169 | // $fruits = array( 170 | // 'date' => 1, 171 | // 'apple' => 5, 172 | // 'banana' => 2, 173 | // 'cherry' => 9 174 | // ); 175 | 176 | // ksort($fruits); 177 | 178 | 179 | // print_r($fruits); 180 | 181 | 182 | 183 | 184 | // ✅ in_array() 185 | 186 | 187 | // $fruits = array('apple', 'banana', 'cherry', 'date'); 188 | 189 | // $searchValue = 'mango'; 190 | 191 | // if (in_array($searchValue, $fruits)) { 192 | // echo "$searchValue exists in the array."; 193 | // } else { 194 | // echo "$searchValue does not exist in the array."; 195 | // } 196 | 197 | 198 | 199 | 200 | // ✅array_search() 201 | 202 | 203 | // $fruits = array('apple', 'banana', 'cherry', 'date'); 204 | // print_r($fruits); 205 | 206 | // $searchValue = 'mango'; 207 | 208 | // $key = array_search($searchValue, $fruits); 209 | 210 | // if ($key !== false) { 211 | // echo "$searchValue was found at index $key in the array."; 212 | // } else { 213 | // echo "$searchValue was not found in the array."; 214 | // } 215 | 216 | 217 | //✅ array_filter 218 | 219 | 220 | // $names = ["John", "Alice", "Bob", "Charlie", "Eve", "David","Ahmed"]; 221 | 222 | // function startsWithA($name) { 223 | // return $name[0] === 'A'; 224 | // } 225 | 226 | // $filteredNames = array_filter($names, 'startsWithA'); 227 | 228 | // print_r($filteredNames); 229 | 230 | 231 | 232 | 233 | //✅ array_map 234 | 235 | // $fnames = ["John", "Alice", "Bob"]; 236 | // $lnames = ["Doe", "Johnson", "Smith"]; 237 | 238 | 239 | // function fullNames($fname) { 240 | // return $fname . ' * ' ; 241 | // } 242 | 243 | 244 | // $names = array_map('fullNames', $fnames); 245 | 246 | 247 | // print_r($names); 248 | 249 | 250 | 251 | // array_reduce 252 | 253 | // $numbers = [1, 2, 3, 4, 5]; 254 | 255 | 256 | // function sum($carry, $item) { 257 | // return $carry + $item; 258 | // } 259 | 260 | 261 | // $totalSum = array_reduce($numbers, 'sum'); 262 | 263 | 264 | // echo "The sum of the numbers is: $totalSum"; 265 | 266 | // ❎❎=================================================================❎❎ 267 | // ❎❎=================================================================❎❎ 268 | // ❎❎=================================================================❎❎ 269 | // ❎❎=================================================================❎❎ 270 | 271 | 272 | // ❎Handling Sting 273 | 274 | // Example1 275 | 276 | // $string = "Hello, World!"; 277 | // $length = strlen($string); 278 | // echo "The length of the string is: " . $length; 279 | 280 | // Example2 281 | 282 | 283 | // $string = "Hello, World!"; 284 | // $lowercase = strtolower($string); 285 | // echo $lowercase; 286 | 287 | // Example3 288 | 289 | 290 | // $string = "Hello, World!"; 291 | // $uppercase = strtoupper($string); 292 | // echo $uppercase; 293 | 294 | // Example4 295 | 296 | 297 | // $string = "Hello, World!"; 298 | // $position = strpos($string, "World"); 299 | // if ($position !== false) { 300 | // echo "Found 'World' at position: " . $position; 301 | // } else { 302 | // echo "Not found"; 303 | // } 304 | 305 | // Example5 306 | 307 | // $string = "Hello, World!"; 308 | // $substring = substr($string, 0, 5); 309 | // echo $substring; 310 | 311 | 312 | // Example6 313 | 314 | // $string = "apple,banana,cherry"; 315 | // $fruitsArray = explode(",", $string); 316 | // print_r($fruitsArray); 317 | 318 | 319 | // Example7 320 | 321 | 322 | // $fruitsArray = ["apple", "banana", "cherry"]; 323 | // $fruitsString = implode(", ", $fruitsArray); 324 | // echo $fruitsString; 325 | 326 | 327 | // Example8 328 | 329 | // $firstName = "John"; 330 | // $lastName = "Doe"; 331 | // $fullName = $firstName . " " . $lastName; 332 | // echo $fullName; // Output: John Doe 333 | 334 | 335 | // Example9 336 | 337 | // $text = " Hello, World! "; 338 | // $trimmedText = trim($text); 339 | // echo $trimmedText; 340 | 341 | // Example 10 342 | 343 | // $text = "Hello, World!"; 344 | // $newText = str_replace("World", "Universe", $text); 345 | // echo $newText; // Output: Hello, Universe! 346 | 347 | 348 | // Example 11 349 | 350 | // $originalString = "Hello, World!"; 351 | // $reversedString = strrev($originalString); 352 | // echo $reversedString; 353 | 354 | 355 | 356 | 357 | // Example 12 Password Generator: 358 | 359 | 360 | // function generatePassword($length) { 361 | // $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+'; 362 | // $password = ''; 363 | 364 | // for ($i = 0; $i < $length; $i++) { 365 | // $password .= $characters[rand(0, strlen($characters) - 1)]; 366 | // } 367 | 368 | // return $password; 369 | // } 370 | 371 | 372 | // echo generatePassword(10); 373 | 374 | 375 | 376 | 377 | // Here are 20 of the most commonly used string functions in PHP: 378 | 379 | // strlen($string) - Returns the length of a string. 380 | // strpos($haystack, $needle) - Finds the position of the first occurrence of a substring in a string. 381 | // str_replace($search, $replace, $string) - Replaces all occurrences of a substring with another substring in a string. 382 | // substr($string, $start, $length) - Returns a portion of a string based on the start position and length. 383 | // strtolower($string) - Converts a string to lowercase. 384 | // strtoupper($string) - Converts a string to uppercase. 385 | // trim($string) - Removes whitespace or other specified characters from the beginning and end of a string. 386 | // str_split($string, $length) - Splits a string into an array of substrings. 387 | // implode($glue, $array) - Joins an array of strings into a single string using a specified delimiter. 388 | // explode($delimiter, $string) - Splits a string into an array of substrings based on a delimiter. 389 | // str_repeat($string, $multiplier) - Repeats a string a specified number of times. 390 | // str_pad($string, $length, $padding, $pad_type) - Pads a string to a specified length with another string. 391 | // strrev($string) - Reverses a string. 392 | // strip_tags($string) - Removes HTML and PHP tags from a string. 393 | // htmlspecialchars($string, $flags) - Converts special characters to their HTML entities. 394 | // strcasecmp($string1, $string2) - Compares two strings, case-insensitive. 395 | // strncasecmp($string1, $string2, $length) - Compares the first n characters of two strings, case-insensitive. 396 | // strchr($haystack, $needle) - Returns the portion of a string from the first occurrence of a substring to the end. 397 | // strcmp($string1, $string2) - Compares two strings, case-sensitive. 398 | // strncasecmp($string1, $string2, $length) - Compares the first n characters of two strings, case-sensitive. 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | -------------------------------------------------------------------------------- /module3/project/tic_tac_toe.php: -------------------------------------------------------------------------------- 1 | = 0 && $row < 3 && $col >= 0 && $col < 3 && $board[$row][$col] == ' ') { 85 | // Make the move 86 | $board[$row][$col] = $player; 87 | 88 | // Check for a win 89 | if (checkWin($board, $player)) { 90 | $winner = $player; 91 | displayBoard($board); 92 | echo "Player $winner wins!\n"; 93 | break; 94 | } 95 | 96 | // Check for a draw 97 | if (checkDraw($board)) { 98 | displayBoard($board); 99 | echo "It's a draw!\n"; 100 | break; 101 | } 102 | 103 | // Switch to the other player 104 | $player = ($player === 'X') ? 'O' : 'X'; 105 | } else { 106 | echo "Invalid move. Try again.\n"; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /module3/string.php: -------------------------------------------------------------------------------- 1 |