SlideShare a Scribd company logo
1 of 43
Introduction in PHP
Part 2
by Bozhidar Boshnakov
Recap
• We talked about
– How to define variables in PHP – with $
– How to define Constants – with define(‘name’,value)
– How to deal with Strings
– Some predefined constants and superglobals
Table of contents
• How to install a Web Server that runs PHP
• How to create PHP files and run them on the browser
and inside the console
• Loops
• Conditional statements
• Functions and return values
• Include and require
• Variables scope
Loops
• PHP supports the C style while loop
– The body of the cycle will be executed until the
condition is met
– The body consists of one or more statements
• If more than one, surrounding brackets are required
– The condition expression is of type boolean
$a = 1;
while ($a < 100) {
$a ++;
echo $a;
}
• The do-while structure is similar to while-do
– The condition is checked after the body is
executed!
– The body is executed at least once!
$a = 1;
do {
$a ++;
echo $a;
} while ($a < 100);
// this will produce 2 3 4 … 100
// the while cycle would output 2 3 4 … 99
• PHP supports C style for cycles
– The for cycle requires initialization, iteration and
ending condition statement
• None of them are obligatory
• Each statement can consist of multiple comma
separated statements
for ($i = 0; $i < 10; $i++)
echo $i;
for ($i = 0, $j = 10; ; $i++, $j--)
if ($j > $i)
echo $i;
else break;
• Foreach is used to iterate over arrays
– For each element in the array the body of the
cycle will be called
– $value will be assigned the value of the current
element in the array
$arr = array (1,1,2,3,5,8);
foreach ($arr as $value)
echo $value;
• Foreach has second form
– Allows you to access the key, corresponding to
the value in the array
$arr = array ("one" => 1, "two" => 2);
foreach ($arr as $key => $value)
echo $key." => ".$value;
• You can leave a cycle with the break
command
• You can move immediately to next cycle
iteration with continue command
$i = 0;
while (true) {
$i ++;
if ($i == 10) break; // exit the cycle
if ($i%2 == 0) continue; // next iteration
echo $i;
}
// will print out 1 3 5 7 9
Conditional Statements
• if construct allows code to be executed only if
certain condition is met
– Note: assignment returns as value the one being
assigned. So we can have
$a = 5; $b = 7;
if ($a > $b)
echo "A is greater than B";
if ($a % 2) {
echo "A is odd";
$b = $a % 2;
echo "A%2 is :".$b;
}
if ($b = $a%2)
echo "A is odd - A%2 is :".$b;
• if-else construct is extension of if construct
and allows you to execute one code if
condition is met or another if not
$a = 5; $b = 7;
if ($a > $b)
echo "A is greater than B";
else
echo "B is greater or equal to A";
• Extension of the if-else construct
– Allows you to add conditions for the else body
– It is similar to writing else if and have two
conditional statements
– You can have multiple elseif statements
if ($a > $b)
echo "A is greater than B";
elseif ($a == $b)
echo "A is equal to B";
else
echo "B is greater than A";
• switch structure allows you to execute
different code, depending on the value of
variable
– It is similar to writing a lot if-s
– The switch body contains "case" clauses
• The engine finds the clause that matches the value
and jumps to that part of the code
switch ($a) {
case 0: echo "A is 0"; break;
case 1: echo "A is 1"; break;
}
• Similar to else, you can have default case in a
switch
– If no case option is found the engine jumps to
the default option
– The default case is not obligatory the last one
switch ($a) {
case 0: echo "A is 0"; break;
case 1: echo "A is 1"; break;
default:
echo "A is … something else";
break;
}
• When the engine moves to the found case it
does NOT exit after the code of that case but
moves on to the next one
– This example will output "A is 0 A is 1"
– The solution is to add break where necessary
– This applies to the default case too
$a = 0;
switch ($a) {
case 0: echo "A is 0";
case 1: echo "A is 1";
}
• Due to the behavior of the switch engine, you
can use empty cases
– They are without break so the engine will jump to
them and move on
– You can use this to combine multiple values with
single code
$a = 0;
switch ($a) {
case 0: echo "A is 0"; break;
case 1:
case 2: echo "A is 1 or 2"; break;
}
• You can use any scalar type of variable
(string, number, boolean, etc)
switch ($name) {
case "Dimitar": echo 1; break;
case "Bozhidar":
case "Boshnakov" : echo 2; break;
case false : echo "No name"; break;
default : echo "?!"; break;
}
• Keep in mind switch uses the loose
comparison "==" and may lead to unexpected
results!
• The solution:
$v = "";
switch (true) {
case ($v === false):
echo "it's boolean false"; break;
case ($v === 0):
echo "it's numeric zero"; break;
case ($v === null):
echo "it's null variable"; break;
case ($v === ""):
echo "it's empty string"; break;
}
• The ternary operator is short version of if-
else construct
– It is used only to return one value or another,
depending on condition
– The syntax is:
– You cannot use it like this:
<condition>?<value if true>:<value if false>
echo ($a<$b ? "a is smaller" : "b is smaller");
echo ($a>$b ? "a" : "b")." is greater";
$b = ($a % 2 ? 17 : 18);
($a > 17 ? echo "a" : echo "b" );
Functions
• Functions are sets of statements, combined
under unique name
– Declare with statement function
– Can accept parameters and return value
– Helps organize and reuse the code
– Echo, print and others are inbuilt functions
function sum ($a, $b) {
return $a + $b;
}
echo sum(5,7); // will output 12
• The name of the function must be unique
• Can accept unlimited number of arguments
– The are defined in brackets after the function
name
• Can return value with return statement
– Accepts one parameter – the return value
• Function can have predefined value for it's
parameters
– Simplifies it's usage
– The default value must be constant expression
– The defaulted arguments must be on the right side in
the function declaration!
function max ($a, $b, $strict = true) {
if (strict)
return ($a > $b);
else
return ($a >= $b);
}
echo max(3,3,false);
echo max(4,3,true);
echo max(3,3); // we can omit 3rd parameter
• By default PHP passes arguments to functions
by value
– This means change of argument value in the
function will not have effect after function ends
– You can force it to pass argument by reference
with & prefix of the argument
function double (&$a) {
$a *= 2;
}
$b = 7;
double ($b);
echo $b; // will return 14;
• PHP supports variable-length function
parameters
– You can pass any number of arguments to the
function
– The function can read the parameters with
func_num_args() and func_get_arg()
function sum(){
$res = 0;
for ($i=0, $n = func_num_args(); $i < $n; $i++)
$res += func_get_arg ($i);
return $res;
}
echo sum (4,5,6);
• Functions can return values with the return
statement
– Accepts only one argument – the value to be
returned
– Exits the function
– To return multiple values you can use arrays
– Function is not obligatory to return value
function foo ($a) {
return true;
// the following code will NOT be executed
echo $a + 1;
}
• You can use fixed-size arrays to return
multiple values and the list statement
– The list statement assigns multiple array items to
variables
• This is NOT a function like array
• Works only for numerical arrays and assumes indexes
start at 0
function small_numbers () {
return array (0,1,2);
}
list ($a, $b, $c) = small_numbers();
• PHP supports variable functions
– If variable name has parentheses appended to it
the engine tries to find function with name
whatever the function value is and executes it
– This doesn't work with some inbuilt functions
like echo, print, etc
function foo () {
echo "This is foo";
}
$a = 'foo';
$a(); // this calls the foo function
• You can check if function is declared with
function_exists(‘name’)
– Useful to create cross-platform scripts
• Functions can be declared inside other
functions
– They do not exist until the outer function is
called
• Functions can be defined conditionally
– Depending on condition function can be defined
or not
Include and Require
• include and require are statements to include
and evaluate a file
– Useful to split, combine and reuse the code
– Both accept single parameter – file name
– If file is not found include produces warning,
require produces fatal error
– File can be with any extension
require "header.php";
echo "body comes here";
require "footer.php";
• include_once and require_once are forms of
include and require
– With include and require you can include one file
many times and each time it is evaluated
– With include_once and require_once if file is
already included, nothing happens
– For instance if in the file you have declared
function, double including will produce error
"Function with same name already exists"
Variables Scope
• Variables outside function are not accessible
in it
– They have to be global or function must declare
it will use them with global
$a = "test";
function $foo () {
echo $a; // this will not output anything
}
$a = "test";
function $foo () {
global $a;
echo $a; // this will output "test";
}
• Variables, declared in loops are accessible
after loop is over
– In the example you have to declare the array
before the loop
for ($i = 0; $i < 5; $i++) {
$arr[] = $i;
}
print_r ($arr); // outputs 5;
$arr = array();
for ($i = 0; $i < 5; $i++) {
$arr[] = $i;
}
print_r ($arr); // works too
• As PHP code can be embedded in HTML,
HTML code can be embedded in PHP code
– This is similar to writing echo "Hello John!";
– Very useful for long texts
<?php
if ($name == "John") {
?>
Hello John!
<?php
}
?>
• Resources
– http://php-uroci.devbg.org/
– http://academy.telerik.com/
– http://www.codecademy.com/
Exercises
1. Write a program that prints the numbers
from 1 to 50
2. Write a program that prints the numbers
from 1 to 50 that are not divisible by 5 and 7
3. Write a program that prints HTML table with
N columns and N rows with the numbers 1,
2, 3, ... in its cells for a given N, defined as a
constant
4. Write a program that finds the minimal
element of an given indexed array
5. Write a program that calculates N! (factorial
1*2*..*N) for a defined constant N
6. Write a program that calculates N!*K!/(N-K)!
for defined constants N and K
7. Write a program that prints the binary
representation of a decimal number N, defined
by a constant
8. Write a program that prints the decimal
representation of a binary number, defined in a
string

More Related Content

What's hot

php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in functiontumetr1
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database ProgrammingAhmed Swilam
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021Ayesh Karunaratne
 
Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in phpAshish Chamoli
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requireTheCreativedev Blog
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance TriviaNikita Popov
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.VimLin Yo-An
 

What's hot (20)

Functions in php
Functions in phpFunctions in php
Functions in php
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in function
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Data Types In PHP
Data Types In PHPData Types In PHP
Data Types In PHP
 
Syntax
SyntaxSyntax
Syntax
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in php
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
DIG1108 Lesson 6
DIG1108 Lesson 6DIG1108 Lesson 6
DIG1108 Lesson 6
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
Php functions
Php functionsPhp functions
Php functions
 

Similar to PHP loops, conditionals, functions

php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptxrani marri
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHPBUDNET
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - phpHung-yu Lin
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics McSoftsis
 
php fundamental
php fundamentalphp fundamental
php fundamentalzalatarunk
 
Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of phppooja bhandari
 
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdfIT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdfpkaviya
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 TrainingChris Chubb
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009cwarren
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 

Similar to PHP loops, conditionals, functions (20)

php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
php fundamental
php fundamentalphp fundamental
php fundamental
 
Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of php
 
php
phpphp
php
 
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdfIT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
 
05php
05php05php
05php
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 Training
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 

More from Bozhidar Boshnakov

PMG Gabrovo - Web Development Level 0 - Introduction
PMG Gabrovo - Web Development Level 0 - IntroductionPMG Gabrovo - Web Development Level 0 - Introduction
PMG Gabrovo - Web Development Level 0 - IntroductionBozhidar Boshnakov
 
QA Challange Accepted - How and why we should use Behat?
QA Challange Accepted - How and why we should use Behat?QA Challange Accepted - How and why we should use Behat?
QA Challange Accepted - How and why we should use Behat?Bozhidar Boshnakov
 
Как да направим живота си по - лесен с добър QA подход
Как да направим живота си по - лесен с добър QA подходКак да направим живота си по - лесен с добър QA подход
Как да направим живота си по - лесен с добър QA подходBozhidar Boshnakov
 

More from Bozhidar Boshnakov (9)

Mission possible - revival
Mission possible - revivalMission possible - revival
Mission possible - revival
 
Web fundamentals 2
Web fundamentals 2Web fundamentals 2
Web fundamentals 2
 
Web fundamentals - part 1
Web fundamentals - part 1Web fundamentals - part 1
Web fundamentals - part 1
 
PMG Gabrovo - Web Development Level 0 - Introduction
PMG Gabrovo - Web Development Level 0 - IntroductionPMG Gabrovo - Web Development Level 0 - Introduction
PMG Gabrovo - Web Development Level 0 - Introduction
 
QA Challange Accepted - How and why we should use Behat?
QA Challange Accepted - How and why we should use Behat?QA Challange Accepted - How and why we should use Behat?
QA Challange Accepted - How and why we should use Behat?
 
DrupalCamp Sofia 2015
DrupalCamp Sofia 2015DrupalCamp Sofia 2015
DrupalCamp Sofia 2015
 
BDD, Behat & Drupal
BDD, Behat & DrupalBDD, Behat & Drupal
BDD, Behat & Drupal
 
Automation in Drupal
Automation in DrupalAutomation in Drupal
Automation in Drupal
 
Как да направим живота си по - лесен с добър QA подход
Как да направим живота си по - лесен с добър QA подходКак да направим живота си по - лесен с добър QA подход
Как да направим живота си по - лесен с добър QA подход
 

Recently uploaded

GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 

Recently uploaded (20)

GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 

PHP loops, conditionals, functions

  • 1. Introduction in PHP Part 2 by Bozhidar Boshnakov
  • 2. Recap • We talked about – How to define variables in PHP – with $ – How to define Constants – with define(‘name’,value) – How to deal with Strings – Some predefined constants and superglobals
  • 3. Table of contents • How to install a Web Server that runs PHP • How to create PHP files and run them on the browser and inside the console • Loops • Conditional statements • Functions and return values • Include and require • Variables scope
  • 5. • PHP supports the C style while loop – The body of the cycle will be executed until the condition is met – The body consists of one or more statements • If more than one, surrounding brackets are required – The condition expression is of type boolean $a = 1; while ($a < 100) { $a ++; echo $a; }
  • 6. • The do-while structure is similar to while-do – The condition is checked after the body is executed! – The body is executed at least once! $a = 1; do { $a ++; echo $a; } while ($a < 100); // this will produce 2 3 4 … 100 // the while cycle would output 2 3 4 … 99
  • 7. • PHP supports C style for cycles – The for cycle requires initialization, iteration and ending condition statement • None of them are obligatory • Each statement can consist of multiple comma separated statements for ($i = 0; $i < 10; $i++) echo $i; for ($i = 0, $j = 10; ; $i++, $j--) if ($j > $i) echo $i; else break;
  • 8. • Foreach is used to iterate over arrays – For each element in the array the body of the cycle will be called – $value will be assigned the value of the current element in the array $arr = array (1,1,2,3,5,8); foreach ($arr as $value) echo $value;
  • 9. • Foreach has second form – Allows you to access the key, corresponding to the value in the array $arr = array ("one" => 1, "two" => 2); foreach ($arr as $key => $value) echo $key." => ".$value;
  • 10. • You can leave a cycle with the break command • You can move immediately to next cycle iteration with continue command $i = 0; while (true) { $i ++; if ($i == 10) break; // exit the cycle if ($i%2 == 0) continue; // next iteration echo $i; } // will print out 1 3 5 7 9
  • 12. • if construct allows code to be executed only if certain condition is met – Note: assignment returns as value the one being assigned. So we can have $a = 5; $b = 7; if ($a > $b) echo "A is greater than B"; if ($a % 2) { echo "A is odd"; $b = $a % 2; echo "A%2 is :".$b; } if ($b = $a%2) echo "A is odd - A%2 is :".$b;
  • 13. • if-else construct is extension of if construct and allows you to execute one code if condition is met or another if not $a = 5; $b = 7; if ($a > $b) echo "A is greater than B"; else echo "B is greater or equal to A";
  • 14. • Extension of the if-else construct – Allows you to add conditions for the else body – It is similar to writing else if and have two conditional statements – You can have multiple elseif statements if ($a > $b) echo "A is greater than B"; elseif ($a == $b) echo "A is equal to B"; else echo "B is greater than A";
  • 15. • switch structure allows you to execute different code, depending on the value of variable – It is similar to writing a lot if-s – The switch body contains "case" clauses • The engine finds the clause that matches the value and jumps to that part of the code switch ($a) { case 0: echo "A is 0"; break; case 1: echo "A is 1"; break; }
  • 16. • Similar to else, you can have default case in a switch – If no case option is found the engine jumps to the default option – The default case is not obligatory the last one switch ($a) { case 0: echo "A is 0"; break; case 1: echo "A is 1"; break; default: echo "A is … something else"; break; }
  • 17. • When the engine moves to the found case it does NOT exit after the code of that case but moves on to the next one – This example will output "A is 0 A is 1" – The solution is to add break where necessary – This applies to the default case too $a = 0; switch ($a) { case 0: echo "A is 0"; case 1: echo "A is 1"; }
  • 18. • Due to the behavior of the switch engine, you can use empty cases – They are without break so the engine will jump to them and move on – You can use this to combine multiple values with single code $a = 0; switch ($a) { case 0: echo "A is 0"; break; case 1: case 2: echo "A is 1 or 2"; break; }
  • 19. • You can use any scalar type of variable (string, number, boolean, etc) switch ($name) { case "Dimitar": echo 1; break; case "Bozhidar": case "Boshnakov" : echo 2; break; case false : echo "No name"; break; default : echo "?!"; break; }
  • 20. • Keep in mind switch uses the loose comparison "==" and may lead to unexpected results! • The solution: $v = ""; switch (true) { case ($v === false): echo "it's boolean false"; break; case ($v === 0): echo "it's numeric zero"; break; case ($v === null): echo "it's null variable"; break; case ($v === ""): echo "it's empty string"; break; }
  • 21. • The ternary operator is short version of if- else construct – It is used only to return one value or another, depending on condition – The syntax is: – You cannot use it like this: <condition>?<value if true>:<value if false> echo ($a<$b ? "a is smaller" : "b is smaller"); echo ($a>$b ? "a" : "b")." is greater"; $b = ($a % 2 ? 17 : 18); ($a > 17 ? echo "a" : echo "b" );
  • 23. • Functions are sets of statements, combined under unique name – Declare with statement function – Can accept parameters and return value – Helps organize and reuse the code – Echo, print and others are inbuilt functions function sum ($a, $b) { return $a + $b; } echo sum(5,7); // will output 12
  • 24. • The name of the function must be unique • Can accept unlimited number of arguments – The are defined in brackets after the function name • Can return value with return statement – Accepts one parameter – the return value
  • 25. • Function can have predefined value for it's parameters – Simplifies it's usage – The default value must be constant expression – The defaulted arguments must be on the right side in the function declaration! function max ($a, $b, $strict = true) { if (strict) return ($a > $b); else return ($a >= $b); } echo max(3,3,false); echo max(4,3,true); echo max(3,3); // we can omit 3rd parameter
  • 26. • By default PHP passes arguments to functions by value – This means change of argument value in the function will not have effect after function ends – You can force it to pass argument by reference with & prefix of the argument function double (&$a) { $a *= 2; } $b = 7; double ($b); echo $b; // will return 14;
  • 27. • PHP supports variable-length function parameters – You can pass any number of arguments to the function – The function can read the parameters with func_num_args() and func_get_arg() function sum(){ $res = 0; for ($i=0, $n = func_num_args(); $i < $n; $i++) $res += func_get_arg ($i); return $res; } echo sum (4,5,6);
  • 28. • Functions can return values with the return statement – Accepts only one argument – the value to be returned – Exits the function – To return multiple values you can use arrays – Function is not obligatory to return value function foo ($a) { return true; // the following code will NOT be executed echo $a + 1; }
  • 29. • You can use fixed-size arrays to return multiple values and the list statement – The list statement assigns multiple array items to variables • This is NOT a function like array • Works only for numerical arrays and assumes indexes start at 0 function small_numbers () { return array (0,1,2); } list ($a, $b, $c) = small_numbers();
  • 30. • PHP supports variable functions – If variable name has parentheses appended to it the engine tries to find function with name whatever the function value is and executes it – This doesn't work with some inbuilt functions like echo, print, etc function foo () { echo "This is foo"; } $a = 'foo'; $a(); // this calls the foo function
  • 31. • You can check if function is declared with function_exists(‘name’) – Useful to create cross-platform scripts • Functions can be declared inside other functions – They do not exist until the outer function is called • Functions can be defined conditionally – Depending on condition function can be defined or not
  • 33. • include and require are statements to include and evaluate a file – Useful to split, combine and reuse the code – Both accept single parameter – file name – If file is not found include produces warning, require produces fatal error – File can be with any extension require "header.php"; echo "body comes here"; require "footer.php";
  • 34. • include_once and require_once are forms of include and require – With include and require you can include one file many times and each time it is evaluated – With include_once and require_once if file is already included, nothing happens – For instance if in the file you have declared function, double including will produce error "Function with same name already exists"
  • 36. • Variables outside function are not accessible in it – They have to be global or function must declare it will use them with global $a = "test"; function $foo () { echo $a; // this will not output anything } $a = "test"; function $foo () { global $a; echo $a; // this will output "test"; }
  • 37. • Variables, declared in loops are accessible after loop is over – In the example you have to declare the array before the loop for ($i = 0; $i < 5; $i++) { $arr[] = $i; } print_r ($arr); // outputs 5; $arr = array(); for ($i = 0; $i < 5; $i++) { $arr[] = $i; } print_r ($arr); // works too
  • 38. • As PHP code can be embedded in HTML, HTML code can be embedded in PHP code – This is similar to writing echo "Hello John!"; – Very useful for long texts <?php if ($name == "John") { ?> Hello John! <?php } ?>
  • 39. • Resources – http://php-uroci.devbg.org/ – http://academy.telerik.com/ – http://www.codecademy.com/
  • 40.
  • 42. 1. Write a program that prints the numbers from 1 to 50 2. Write a program that prints the numbers from 1 to 50 that are not divisible by 5 and 7 3. Write a program that prints HTML table with N columns and N rows with the numbers 1, 2, 3, ... in its cells for a given N, defined as a constant 4. Write a program that finds the minimal element of an given indexed array
  • 43. 5. Write a program that calculates N! (factorial 1*2*..*N) for a defined constant N 6. Write a program that calculates N!*K!/(N-K)! for defined constants N and K 7. Write a program that prints the binary representation of a decimal number N, defined by a constant 8. Write a program that prints the decimal representation of a binary number, defined in a string