PHP Syntax Data Types, Variables, Operators, Expressions, Conditional Statements SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Advertisements

0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
JavaScript, Fourth Edition
ASP.NET Programming with C# and SQL Server First Edition
JavaScript, Third Edition
Introduction to C Programming
Integer, Floating-Point, Text Data, Variables, Literals Svetlin Nakov Telerik Corporation
Performing Simple Calculations with C# Svetlin Nakov Telerik Corporation
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Chapter 4 – The Building Blocks Data Types Literals Variables Constants.
A Review of Programming and C++
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
JavaScript Syntax Data Types, Variables, Operators, Expressions, Conditional Statements Svetlin Nakov Technical Trainer Software University.
Primitive Data Types and Variables Integer, Floating-Point, Text Data, Variables, Literals Angel Georgiev Part-time Trainer angeru.softuni-friends.org.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
1 Working with Data Types and Operators. 2 Using Variables and Constants The values stored in computer memory are called variables The values, or data,
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Chapter 2: Using Data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Introduction to PHP A user navigates in her browser to a page that ends with a.php extension The request is sent to a web server, which directs the request.
Open Source Software Unit – 3 Presented By Mr. R.Aravindhan.
Primitive Data Types and Variables Integer, Floating-Point, Text Data, Variables, Literals SoftUni Team Technical Trainers Software University
C++ Programming: Basic Elements of C++.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Perform Calculations and Control Flow Telerik Software Academy Learning & Development Team.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
JavaScript Syntax Data Types, Variables, Operators, Expressions, Conditional Statements SoftUni Team Technical Trainers Software University
Telerik Software Academy Telerik School Academy Integer, Floating-Point, Text Data, Variables,
1 PHP Introduction Chapter 1. Syntax and language constructs.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Performing Simple Calculations with C# Telerik Corporation
PHP Programming with MySQL Slide 3-1 CHAPTER 3 Working with Data Types and Operators.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Basics.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 14 JavaScript: Part II The Web Warrior Guide to Web Design Technologies.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
1 PHP Intro PHP Introduction After this lecture, you should be able to: Know the fundamental concepts of Web Scripting Languages in general, PHP in particular.
Session 2: PHP Language Basics iNET Academy Open Source Web Development.
Operators and Expressions
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Data Types, Variables, Operators, Expressions, Conditional Statements
BASIC ELEMENTS OF A COMPUTER PROGRAM
Numeral Types and Type Conversion
Java Programming: From Problem Analysis to Program Design, 4e
Java - Data Types, Variables, and Arrays
Chapter 2: Basic Elements of Java
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Presentation transcript:

PHP Syntax Data Types, Variables, Operators, Expressions, Conditional Statements SoftUni Team Technical Trainers Software University

2 1.Data Types in PHP  Integer, Floating-Point, Boolean, String 2.Declaring and Using Variables 3.Operators, Expressions, Statements 4.Conditional Statements  If-else, switch-case 5.False-like Conditions 6.Accessing Forms Fields Table of Contents

PHP Introduction

4  PHP (PHP Hypertext Preprocessor) is server-side scripting language used for creating dynamic web content  First introduced in 1995 as module for Apache  Free and open-source, written in C  Can be deployed on almost any operating system  Provides interaction with Databases (CRUDs)  Can be embedded in HTML What is PHP?

5 PHP – Example My first PHP code! My first PHP code! <?php $myName = 'Yordan'; $myName = 'Yordan'; echo 'My name is '. $myName; echo 'My name is '. $myName; ?> ?> Code is enclosed with Code is enclosed with tags

Mixing PHP and HTML  PHP is designed to mix HTML and PHP code:  This is similar to writing echo "Hello John!";  Very useful for long texts Hello John! Hello John! You are not John. You are not John.

Data Types in PHP

8  A data type:  Is a domain of values of similar characteristics  Defines the type of information stored in the computer memory (in a variable)  PHP supports eight types:  Scalar: Boolean, Integer, Floating point, String  Compound: Array, Object  resource and NULL  PHP is a "type-less" language What Is a Data Type?

9  PHP is a typeless language  The variable types are not explicitly defined  The type of a variable can be changed at runtime  Variables in PHP are declared with the symbol $ PHP Data Types $count = 5; // variable holds an integer value $count = 'hello'; // the same variable now holds a string $name = 'Svetlin Nakov'; // variable holds a string $mark = 5.25; // mark holds a floating-point number

10  Integer types represent whole numbers  The size of an integer is platform-dependent  32-bit: to  64-bit: to  In Windows it is always 32-bit  Too large values for integer type are automatically turned into a floating-point number Integer Numbers $maxInteger = ; $maxInteger = ; echo gettype($maxInteger); // integer $maxInteger += 1; echo gettype($maxInteger); // double

11  Floating-point types represent real numbers, e.g  In PHP the floating-point numbers are 64-bit  Stored in the IEEE format  Have range from -1.79e+308 to 1.79e+308  Have precision of 15 digits  Can behave abnormally in the calculations  E.g = Floating-Point Numbers

 Convert floating-point to integer number  Convert to integer number with rounding  Convert string to integer Numbers Conversion $variable = 5; $floatVar = floatval($variable); // Or: // Or: $floatVar = (float)$variable; $floatVar = (float)$variable; $variable = ; $varInt = intval($variable); // Or: $varInt = (int)$variable; $num = "3.14"; $int = (int)$num; $float = (float)$num;

13  Has two possible values: true and false  Values are case-insensitive (True, true, TRUE & False, false, FALSE)  Is useful in logical expressions  Returns "1" or "null"  Example of Boolean variables: The Boolean Data Type echo(true); // 1 echo(false); // (nothing) var_dump(true); // bool(true) var_dump(false); // bool(false)

14  The string data type represents a sequence of characters  Strings are enclosed in quotes:  Both ' and " work correctly, with “anomalies”  Best practices suggest using single quotes  Strings can be concatenated (joined together)  Using the. (dot) operator The String Data Type $string = 'Welcome to PHP'; $name = 'Soft'. ' '. 'Uni';

 Single-quoted strings do not interpolate variables:  Double-quoted string interpolate variables:  Curly braces ensures the correct variable is interpolated Variable Interpolation $name = 'Fred'; echo 'Hello, $name'; // Hello, $name $who = 'Svetlin'; $where = 'here'; echo "$who was $where"; // Svetlin was here $n = 12; echo "You are the {$n}th person";

16  An array holds a group of values, which you can identify by position or identifying name  Arrays with number identifiers (with zero being the first position)  Associative arrays with string identifiers Array Type $students[0] = "Dean"; $students[1] = "Vladislav"; $students = array("Dean", "Vladislav"); $students['Dean'] = 6; $students['Vladislav'] = 5; $students = array('Dean' => 6, 'Vladislav' => 5);

17  A class is a definition of a structure  Contains properties (variables) and methods (functions)  Once a class is defined, any number of objects can be made from it with the new keyword  Object’s properties/methods can be accessed with the -> construct Object Type $svetlin = new Person; $svetlin->name('Svetlin'); echo "Hello, {$svetlin->name}\n"; class Person { public $name; public $name; function name ($newname) { function name ($newname) { $this->name = $newname; $this->name = $newname; }}

18  Special variable, holding a reference to an external resource  E.g. opened file, database connection, image canvas area  Resources are created and used by special functions.  Resource with no more references to it is detected automatically  It is freed by the garbage collector  is_resource() function checks whether a value is a resource Resource Type $res = database_connect(); // database connect function database_query($res); $res = "boo"; // database connection automatically closed because $res is redefined

Null Values What is NULL in PHP?

 In PHP there is a special value NULL  Undefined means that a variable is declared but not initialized  Null means that an object exists and is empty (has no value)  All variables can be reset to null with unset() Null Value <?php $variable; // variable is undefined $variable = 4; // variable has value 4 $variable = NULL; // variable has no value unset($variable); // unset($variable); // variable is undefined?>

 The variable type can be checked with gettype()  Or just print it with var_dump()  Great for checking the type and value of a given variable in the code Checking the Type of a Variable $boolVariable = true; gettype($boolVariable); // boolean $intVariable = 123; gettype($intVariable); // integer $stringVariable = "SoftUni"; gettype($stringVariable); // string $b = true; var_dump($b); // boolean(true) $i = 123; var_dump($i); // integer(123) $s = "PHP"; var_dump($s); // string("PHP")

Data Types in PHP Live Demo

Declaring and Using Variables p q i

24  A variable is a:  Placeholder of information that can be changed at run-time  A piece of computer memory holding some value  Variables allow you to:  Store information  Retrieve the stored information  Change the stored information What Is a Variable? p q i

25  A variable has:  Name  Type (of stored data)  Value  Example:  Name: $counter  Type: integer  Value: 5 Variable Characteristics $counter = 5;

26  When declaring a variable we:  Specify its name (called identifier)  The type is inferred by the value  Give it an initial value  Examples: Declaring Variables $height = 200; $str = 'Hello'; $isPositive = true;

27  Identifiers may consist of:  Letters, digits [0-9], underscore '_'  Cannot start with a digit  Cannot be a PHP keyword  Identifiers in PHP are case-sensitive  Identifiers should have a descriptive name  Only Latin letters  Variables and functions names: use camelCase Identifiers

28  Examples of correct identifiers:  Examples of incorrect identifiers: Identifiers – Examples $2Pac = 2; // Cannot begin with a digit function new() { return 5; } // new is a keyword $New = 2; // Here N is capital, so it's not a PHP keyword $_2Pac = 2; // This identifier begins with _ $поздрав = 'Hello'; // Unicode symbols used $greeting = 'Hello'; // This is more appropriate $n = 100; // Undescriptive $number_of_clients = 100; // Descriptive // Overdescriptive identifier: $numberOfPrivateClientOfTheFirm = 100;

29  The = operator is used to assign a value to a variable: Assigning Values // Assign a value (literal) to a variable $firstValue = 5; // Using an already declared variable: $secondValue = $firstValue; // Cascading assignment $thirdValue = $newValue = 3;

30  Reference the value of a variable whose name is stored in another variable by prefacing the variable reference  After the second statement executes, the variable $first has the value " second " Variable Variables // variable variables example $variable = "first"; $$variable = "second"; echo $variable; // first echo $first // second echo $$variable // second

31  References are how you create variable aliases  Variable References $firstName = "Nakov"; $secondName =& firstName; $secondName = "Karamfilov"; echo $firstName; // Karamfilov echo $secondName; // Karamfilov

32  A variable in PHP can be:  undefined  NULL  Local  Example: In this code secondVar is undefined: Variables in PHP echo($asfd); // Error $p = null; echo($p); // nothing is printed $localVar = 5; ($localVar); // 5 $localVar = 5; echo($localVar); // 5 $firstVar = 10; echo($firstVar); // 10 echo($secondVar); // Undefined variable: secondVar

Variable Scope Local, Global, Static

34  Local scope: a variable declared in a function is local to that function  Visible only to code in that function  Not accessible outside of the function  Variables defined outside a function (called global variables) are not accessible inside the function Local Scope function updateCounter() { $counter++; $counter++;} $counter = 10; updateCounter(); echo $counter; // 10

35  Variables declared outside a function are global  Can be accessed from any part of the program  Use the global keyword inside the function to access global variables  Cumbersome way to update the global variable is to use PHP’s $GLOBALS : $GLOBALS[counter] Global Scope function updateCounter() { global $counter; global $counter; $counter++; // or $GLOBALS[counter]++; $counter++; // or $GLOBALS[counter]++;} $counter = 10; updateCounter(); echo $counter; // 11

36  Static variables retain their values between calls to a function  Visible only within the function where defined  Declare a variable static with the static keyword Static Variables function updateCounter() { static $counter = 0; static $counter = 0; $counter++; $counter++; echo "Static counter: {$counter}\n"; echo "Static counter: {$counter}\n";} $counter = 10; updateCounter();updateCounter(); echo "Global counter: {$counter}\n"; Output: Static counter: 1 Static counter: 2 Global counter: 10

PHP Constants  In PHP constants are defined with the define function  Constant values cannot be changed  Doesn't start with $  Can hold any scalar value

Operators in PHP Arithmetic, Logical, Comparison, Assignment, …

39  Operator is an operation performed over data at runtime  Takes one or more arguments (operands)  Produces a new value  Operators have precedence  Precedence defines which will be evaluated first  Operators are used to build expressions  Expressions are sequences of operators and operands that are evaluated to a single value What is an Operator?

40 CategoryOperators Arithmetic + - * / % Logical && || ^ ! Binary & | ^ ~ > Comparison == != = === !== Assignment = += -= *= /= %= &= |= ^= >= String concatenation + Other. [] () ?: new Categories of Operators in PHP

41 PrecedenceOperators Highest () (postfix) new typeof (prefix) + - (unary) ! * / % + - > > = = == != Lower & Operators Precedence

42 PrecedenceOperators Higher ^ | && || ?: Lowest = *= /= %= += -= >= &= ^= |= Operators Precedence (2)  Parenthesis operator always has the highest precedence  Note: prefer using parentheses, even when it seems stupid to do so

43  Arithmetic operators +, -, *, / are the same as in math  The division operator / returns number  Division / 0 returns false and "Division by zero" warning  Remainder operator % returns the remainder from division  E.g. 5 % 3  2  The operator ++ / -- increments / decrement a variable  Prefix ++ vs. postfix ++ Arithmetic Operators

44  Logical operators take boolean operands and return boolean result  Operator ! turns true to false and false to true  Behavior of the operators &&, || and ^ (1 == true, 0 == false): Logical Operators Operation||||||||&&&&&&&&^^^^ Operand Operand Result

45  Bitwise operators in PHP always work for 32-bit integers  Bitwise operator ~ turns all 0 to 1 and all 1 to 0  Like ! for boolean expressions but works bit by bit  The operators |, & and ^ behave like bitwise ||, && and ^  The > move the bits (left or right)  Behavior of the operators |, & and ^: Bitwise Operators Operation||||&&&&^^^^ Operand Operand Result

46  Comparison operators are used to compare variables  ==,, >=, <=, !=, ===, !==  The == means "equal after type conversion"  The === means "equal and of the same type" Comparison Operators $a = 5; $b = 4; var_dump($a >= $b); // bool(true) var_dump($a != $b); // bool(true) var_dump($a == $b); // bool(false) var_dump($a == "5"); // bool(true) var_dump($a === "5"); // bool(false)

47  Assignment operators are used to assign a value to a variable  =, +=, -=, |=,...  Assignment operators examples: Assignment Operators $x = 6; $y = 4; echo($y *= 2); // 8 $z = $y = 3; // $y = 3; $z = 3; echo($z); // 3 echo($x |= 1); // 7 echo($x += 3); // 10 echo($x /= 2); // 5

48  String concatenation operator. is used to concatenate strings  If the second operand is not a string, it is converted to string automatically  Member access operator -> is used to access object members  Square brackets [] are used with arrays to access element by index  Parentheses () are used to override the default operator precedence Other Operators $output = "The number is : "; $number = 5; echo($output. $number); // The number is : 5

49  Conditional operator ?: has the form:  If b is true then the result is x, else the result is y  Also called ternary operator  The new operator is used to create new objects  this operator references the current context Other Operators (2) $b ? $x : $y

50 Other Operators (3) $a = 6; $b = 4; echo($a > $b ? "a > b" : "b >= a"); // a > b echo "SoftUni" == "SoftUni" ? "Equal" : "Not Equal"; $c = $b = 3; // b = 3; followed by c = 3; echo($c); // 3 echo(($a + $b) / 2); // 4.5 echo(gettype($a)); // integer echo(gettype([])); // array

Operators in PHP Live Demo

Expressions

53  Expressions are:  Sequences of operators, literals and variables that are evaluated to some value  Examples: Expressions $r = ( ) / 2 + 5; // r = 70 // Expression for calculation of circle area $surface = pi() * $r * $r; // Expression for calculation of circle perimeter $perimeter = 2 * pi() * $r;

If and If-else Implementing Conditional Logic

55  PHP implements the classical if / if-else statements: Conditional Statements: if-else $number = 5; if ($number % 2 == 0) { echo("This number is even."); echo("This number is even.");} else { echo("This number is odd."); echo("This number is odd.");}

56 Alternative If Syntax <?php $a == 5; $a == 5; if ($a == 5): if ($a == 5): echo "a equals 5"; echo "a equals 5"; echo "..."; echo "..."; elseif ($a == 6): elseif ($a == 6): echo "a equals 6"; echo "a equals 6"; echo "!!!"; echo "!!!"; else: else: echo "a is neither 5 nor 6"; echo "a is neither 5 nor 6"; endif; endif;?>  PHP offers an alternative syntax for the if-statement:

if and if-else Live Demo

switch-case Making Several Comparisons at Once

59  Selects for execution a statement from a list depending on the value of the switch expression The switch-case Statement switch ($day) { case 1: echo('Monday'); break; case 2: echo('Tuesday'); break; case 3: echo('Wednesday'); break; case 4: echo('Thursday'); break; case 5: echo('Friday'); break; case 6: echo('Saturday'); break; case 7: echo('Sunday'); break; default: echo('Error!'); break; }

60 1.The expression is evaluated 2.When one of the constants specified in a case label is equal to the expression:  The statement that corresponds to that case is executed 3.If no case is equal to the expression:  If there is default case, it is executed  Otherwise the control is transferred to the end point of the switch statement 4.The break statement exits the switch-case statement How switch-case Works?

61 Alternative Switch Syntax $variable = 2; switch ($variable): case 1: case 1: echo " News "; echo " News "; break; break; case 2: case 2: echo " Forum "; echo " Forum "; break; break;endswitch;  PHP offers an alternative syntax for switch constructs:

The switch-case Statement Live Demo

Accessing Form Fields from PHP Reading and Writing Form Data

64  You can access the form fields by their name property  HMTL:  PHP: Accessing Forms Fields Name: Name: </form> Welcome Welcome Your is: Your is:

Accessing Form Fields Live Demo

66  PHP dynamic data types  number, string, boolean, null, array, object  Operators are similar to C#, Java and C++  Expressions are as in C#, Java and C++  If-else statements are as in C#, Java and C++  Alternative syntax: if-elseif-endif  Switch-case statement are similar to Java / C#  Form fields can be accessed by $_GET['key'] and $_POST['key'] Summary

? ? ? ? ? ? ? ? ? PHP Syntax

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 68

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg