Chapter 3 PHP Basics PDF

Summary

This document outlines the basics of PHP programming and includes information on server-side scripting, architecture, and features. It also discusses different types of variables in PHP and how to declare them. It is likely part of a course in web programming.

Full Transcript

Chapter 3: PHP Basics Chapter’s Objectives 1. Understand PHP as a server-side scripting language. 2. Differentiate scripting languages from programming languages. 3. Explore PHP's architecture, features, and community. 4. Learn PHP syntax and script embedding in HTML. 5. Set up tools for runnin...

Chapter 3: PHP Basics Chapter’s Objectives 1. Understand PHP as a server-side scripting language. 2. Differentiate scripting languages from programming languages. 3. Explore PHP's architecture, features, and community. 4. Learn PHP syntax and script embedding in HTML. 5. Set up tools for running PHP scripts. 6. Master code commenting for readability. 7. Work with variables, data types, and constants. 8. Use operators effectively in PHP. 9. Output content using `echo` and `print`. 10. Handle strings and common string functions. 11. Implement conditional statements for decision-making. 12. Utilize loops for repetitive tasks. 13. work with arrays 14. Create and use functions for code modularity. 15. Understand parameter passing in functions. 16. Implement default parameter values for flexibility. Web Programming2 Ch03 1 2.1 PHP Definition & Syntax What is PHP?  PHP is a server-side scripting language. that is used to develop dynamic Web applications.  PHP stands for the recursive backronym “PHP: Hypertext Preprocessor”. Scripting Language  Scripting languages are typically interpreted rather than compiled, which means that the code is executed directly by an interpreter at runtime, line by line, without the need for a separate compilation step.  The purpose of the scripts is usually to perform routine tasks for an application.  Server-side scripts are interpreted on the server while client-side scripts are interpreted by the client application.  PHP is a server side script that is interpreted on the server while JavaScript is an example of a client side script that is interpreted by the client browser. Both PHP and JavaScript can be embedded into HTML pages. Programming Language Vs Scripting Language: Programming language Scripting language Has all the features needed to develop Mostly used for routine tasks complete applications. The code must be compiled before it can be The code is usually executed without executed compiling Does not need to be embedded into other Is usually embedded into other software languages environments. Web Programming2 Ch03 2 PHP Architecture Figure 2.1: PHP Architecture PHP Features  Cross-platform: it can be used on a variety of operating systems.  Free and open source: it is freely available for anyone to use and modify.  Secure: PHP has several security features which help to protect your website from attacks.  Large community: If you have any questions or problems, you can easily find help from other developers.  Short learning curve. Web Programming2 Ch03 3 PHP Syntax  A PHP script starts with :  The default file extension for PHP files is ".php".  A PHP file normally contains HTML tags, and some PHP scripting code. Example Output Hello World! Note: PHP statements end with a semicolon (;). Web Programming2 Ch03 4 Tools needed to run PHP scripts. To run PHP scripts, you need the following tools. 1. Web server: A web server is a software application that delivers web pages to users. There are many different web servers available, such as Apache, Nginx, and IIS. 2. PHP interpreter: A PHP interpreter is a software application that executes PHP code. The PHP interpreter is usually installed on the web server. 3. Text editor: A text editor is a software application that is used to create and edit text files. There are many different text editors available, such as Notepad, Sublime Text, and Visual Studio Code. 4. Internet browser: such as Google chrome, Firefox, etc. to display output. 2.2 PHP Comments A comment in PHP is a piece of text that is ignored by the PHP parser. Comments are used to explain the code, to make it easier to read and understand. There are two types of comments in PHP: 1. Single-line comments: Single-line comments start with a // and end at the end of the line. 2. Multi-line comments: Multi-line comments start with. For example, the following code contains a single-line comment: // This is a single-line comment. Web Programming2 Ch03 5 The following code contains a multi-line comment: 2.3 PHP Variables & Datatypes  Variables are used to store data, like string of text, numbers, etc.  The data or value stored in the variables can be set, updated, and retrieved whenever needed. Variable Declaration  To declare a variable in PHP, you use the $ sign followed by the name of the variable.  For example, the following code declares two variables:  The first variable, $name, stores the value "Ahmed Ali". The second variable, $age, stores the value 30.  To assign a value to a variable, you use the equal sign (=)  Note: When you assign a text value to a variable, put quotes around the value. Web Programming2 Ch03 6 Variable Rules Here are some of the rules for PHP variables:  Variable names must start with a letter or an underscore.  Variable names can only contain letters, numbers, and underscores.  Variable names cannot be reserved words.  Variable names are case-sensitive. Getting the value of a variable in PHP To get the value of a variable in PHP, you use the variable name itself For example, the following code gets the value of the variable $name and prints it to the screen: Example Output Ahmed Ali Datatypes A Data type is the classification of data into a category according to its value. PHP has several data types of variables. The most Common are: Web Programming2 Ch03 7  Scalar types: These are the most basic data types and represent a single value. o Integer: A whole number, positive or negative. o Float: A number with a decimal point. o String: A sequence of characters. o Boolean: A value that can be either true or false.  Compound types: These are data types that can contain multiple values. o Array: A collection of data items. o Object: A data type that represents an instance of a class.  Special types: These are data types that do not fit into the other categories. o Null: A value that represents nothing. o Resource: A reference to an external resource, such as a file or database. Here are some examples of how data types are used in PHP: Note: As shown in the previous examples, PHP is a loosely typed language, which means that variables do not need to be declared with a specific data type. 2.4 PHP constant  A PHP constant is an identifier (name) for a simple value.  The value of constant cannot be changed during the script.  A valid constant name starts with a letter or underscore (no $ sign before the constant name). How to define a PHP constant? define('CONSTANT_NAME', VALUE); For example, the following code defines a constant named PI with the value of 3.14159: define('PI', 3.14159); How to use a PHP constant? To use a PHP constant, you simply use its name. For example, the following code prints the value of the PI constant: echo PI; Web Programming2 Ch03 9 2.5 PHP Operators Operators are used to perform operations on variables and values. PHP divides the operators in the following groups: Arithmetic operators Assignment operators Comparison operators Increment/Decrement operators Logical operators String operators Array operators Conditional assignment operators PHP Arithmetic Operators The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc. Operator Name Example Result + Addition $x + $y Sum of $x and $y - Subtraction $x - $y Difference of $x and $y * Multiplication $x * $y Product of $x and $y / Division $x / $y Quotient of $x and $y % Modulus $x % $y Remainder of $x divided by $y Web Programming2 Ch03 10 PHP Assignment Operators The PHP assignment operators are used with numeric values to write a value to a variable. Assignment Same as... Description x=y x=y The left operand gets set to the value of the expression on the right x += y x=x+y Addition x -= y x=x–y Subtraction x *= y x=x*y Multiplication x /= y x=x/y Division x %= y x=x%y Modulus PHP Comparison Operators PHP comparison operators are used to compare two values (number or string): Operator Name Example Result == Equal $x == $y Returns true if $x is equal to $y === Identical $x === $y Returns true if $x is equal to $y, and they are of the same type != Not equal $x != $y Returns true if $x is not equal to $y Web Programming2 Ch03 11 Not equal $x $y Returns true if $x is not equal to $y !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type > Greater than $x > $y Returns true if $x is greater than $y < Less than $x < $y Returns true if $x is less than $y >= Greater than or $x >= $y Returns true if $x is greater than or equal to equal to $y Single Quotes vs. Double Quotes  Single quotes (') treat everything within them as a literal string, and variables are not expanded.  Double quotes (") allow variable interpolation, where variables are evaluated, and their values are inserted into the string. Example Output Hello, $name Hello, Sara Web Programming2 Ch03 16 Concatenation In PHP, the concatenation operator is used to combine strings or values together. The concatenation operator is represented by a period (`.`). It allows you to create a single string by joining two or more strings or variables. Here are some examples: Example1: Concatenating Two Strings. Output Ali Asiri Example2: Concatenating String and Variable. Output The iPhone costs $999. Web Programming2 Ch03 17 Example3: Using `.=` operator. Output Saudi Arabia. o In this example, we used the `.=` operator to concatenate the second part of the country name to the existing `$country` variable. String Functions PHP provides a wide range of built-in string functions that help you manipulate and work with strings. Some commonly used string functions include: strlen The strlen function calculates the length of a string. Example Web Programming2 Ch03 18 Output Length of the string: 13 substr The substr function is used to extract a portion of a string. Example Output Substring: Hello str_replace The str_replace function replaces all occurrences of a search string with a replacement string in a given string. Example Web Programming2 Ch03 19 Output I love bananas. bananas are delicious. 2.8 Conditional Statements in PHP Conditional statements allow us to perform action based in some type of condition. PHP provides the following types of conditional statements: 1- if statement 2- if…else statement 3- if… else if… else Statement 4- Switch statement 1- if statement The if statement is a conditional statement that executes a block of code when a condition is true. Syntax if (condition) { // Execute this code when condition is true } Example Web Programming2 Ch03 20 Output The number is positive 2. if…else statement if statement can be followed by an optional else statement to execute a block of code when the condition in the if statement evaluates to false. Syntax if (condition) { // Execute this code when the condition is true. else{ // Execute this code when the condition is false. } Example Output The number is negative Web Programming2 Ch03 21 3. if…elseif…else statement An if-else-if statement is a conditional statement that can have multiple conditions. Syntax if (condition1) { // Code to be executed if condition1 is true } else if (condition2) { // Code to be executed if condition2 is true -- -- -- } else { // Code to be executed if neither condition1 nor condition2 is true }  The conditions are evaluated in order, and the first condition that evaluates to true will cause the corresponding block of code to be executed.  If none of the conditions evaluate to true, then the last block of code (the else statement) will be executed. Example Web Programming2 Ch03 22 Output The number is equal to 10 4. Nested if statements Nested if statements are if statements that are placed inside other if statements. This can be useful for situations where you need to check multiple conditions in order to determine what code to execute. Example Output You are an adult male. Web Programming2 Ch03 23 5. Switch statement Switch statement is a control-flow statement that tests the value of expression against multiple cases. Syntax switch (expression) { case value1: //this code will execute if the case matches the expression break; case value2: //this code will execute if the case matches the expression break; case value3: //this code will execute if the case matches the expression break; default: //this code will execute if none of the cases match the expression break; }  The computer will go through the switch statement and check for equality between the case and expression. If one of the cases matches the expression, then the code inside that case clause will execute.  If none of the cases match the expression, then the default clause will be executed.  The break statement transfers control to the end of the switch statement when one case is matched. Web Programming2 Ch03 24 Example

Use Quizgecko on...
Browser
Browser