SlideShare a Scribd company logo
Variables in PHP
Variables in PHP Variables in PHP are denoted by a dollar sign followed by the name of the variable.  A variable name is case-sensitive.  A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
Example Usage of Variables <html> <head> <title>Greetings</title> </head> <body> <h1>Greetings</h1> <p> <?php  $person  = &quot;Tom&quot;; $Person  = &quot;Dick&quot;; echo &quot;Hello  $person  and  $Person &quot;; ?> </p> </body> </html>
 
Data Types in PHP PHP supports eight primitive data types There are four scalar types boolean integer floating-point number string There are two structured types array object There are two special data types resource NULL The programmer does not specify the type of a variable a  variable’s type is determined from the context of its usage
Booleans The boolean data type admits two values true (case-insensitive) false (case-insensitive) Example usage $itIsRainingToday = true; $thePrinterIsBusy = True; $theQueueIsEmpty = FALSE;
Integers Integers can be specified in decimal, hexadecimal  or octal notation, optionally preceded by a sign  In  octal notation, the number  must have a leading   0 In  hexadecimal notation , the number must have a leading  0x.  Example s $a =  1234 ;  # decimal number $a =  -123 ;  # a negative number $a =  0123 ;  # octal number (equivalent to 83 decimal) $a =  0x1 B ;  # hexadecimal number (equivalent to 2 7  decimal) The  maximum  size of an integer is platform-dependent,  but usually it’s  32 bits signed  – about 2,000,000,000 PHP  does not support   unsigned integers.
Floating Point Numbers These can be specified using any of these forms : $a = 1.234;  $a = 1.2e3;  $a = 7E-10; The  maximum  size of a float is platform-dependent, although  most support a maximum of about  1.8e308 with a precision of roughly 14 decimal digits
Strings A string literal can be specified in three different ways :   single quoted  double quoted  heredoc syntax
Double-quoted Strings In double-quoted strings,  variables are interpreted to their values, and various characters can be escaped \n  linefeed \r  carriage return \t  horizontal tab \\  backslash \$  dollar sign \”  double quote \[0-7]{1,3}  a character in octal notation \x[0-9A-Fa-f]{1,2}  a character in hexadecimal notation
Single-quoted Strings In single-quoted strings, single-quotes and backslashes must be escaped with a preceding backslash Example usage echo 'this is a simple string'; echo 'You c an  embed newlines in strings, just  like  this .'; echo ‘ Douglas MacArthur said  &quot;I\'ll be back ” when leaving the Phillipines '; echo 'Are you sure you want to delete C:\\*.*?';
Heredoc Strings Heredoc strings are like double-quoted strings without the double quotes A heredoc string is delimited as follows The string is preceded by <<< followed by a label The string followed by a 2 nd  occurrence of the same label Example usage $str =  <<<EOD Example of string spanning multiple lines using heredoc syntax. EOD ;
String-manipulation functions PHP provides huge range of string-manipulation functions: addcslashes -- Quote string with slashes in a C style addslashes -- Quote string with slashes bin2hex  --  Convert binary data into hexadecimal representation  chop -- Alias of rtrim() chr  -- Return a specific character chunk_split -- Split a string into smaller chunks convert_cyr_string --  Convert from one Cyrillic character set to another  count_chars --  Return information about characters used in a string  crc32 -- Calculates the crc32 polynomial of a string crypt  -- One-way string encryption (hashing) echo  -- Output one or more strings explode -- Split a string into an array get_html_translation_table --  Returns the translation table used by htmlspecialchars() and htmlentities()
get_meta_tags --  Extracts all meta tag content attributes from a file and returns an array  hebrev --  Convert logical Hebrew text to visual text  hebrevc --  Convert logical Hebrew text to visual text with newline conversion  htmlentities  --  Convert all applicable characters to HTML entities  htmlspecialchars --  Convert special characters to HTML entities  implode – creates a string from array elements join -- Join array elements with a string levenshtein --  Calculate Levenshtein distance between two strings  localeconv -- Get numeric formatting information ltrim  --  Strip whitespace from the beginning of a string  md5  -- Calculate the md5 hash of a string md5_file -- Calculates the md5 hash of a given filename metaphone -- Calculate the metaphone key of a string nl2br --  Inserts HTML line breaks before all newlines in a string  ord  -- Return ASCII value of character parse_str -- Parses the string into variables print  -- Output a string printf  -- Output a formatted string
quoted_printable_decode --  Convert a quoted-printable string to an 8 bit string  quotemeta -- Quote meta characters str_rot13 -- Perform the rot13 transform on a string rtrim  --  Strip whitespace from the end of a string  sscanf  --  Parses input from a string according to a format  setlocale -- Set locale information similar_text  --  Calculate the similarity between two strings  soundex -- Calculate the soundex key of a string sprintf  -- Return a formatted string strncasecmp --  Binary safe case-insensitive string comparison of the first n characters  strcasecmp --  Binary safe case-insensitive string comparison  strchr  --  Find the first occurrence of a character  strcmp  -- Binary safe string comparison strcoll -- Locale based string comparison strcspn --  Find length of initial segment not matching mask  strip_tags -- Strip HTML and PHP tags from a string stripcslashes --  Un-quote string quoted with addcslashes()  stripslashes --  Un-quote string quoted with addslashes()
stristr  --  Case-insensitive strstr()  strlen  -- Get string length strnatcmp --  String comparisons using a &quot;natural order&quot; algorithm  strnatcasecmp --  Case insensitive string comparisons using a &quot;natural order&quot; algorithm  strncmp  --  Binary safe string comparison of the first n characters  str_pad --  Pad a string to a certain length with another string  strpos  --  Find position of first occurrence of a string  strrchr  --  Find the last occurrence of a character in a string  str_repeat  -- Repeat a string strrev  -- Reverse a string strrpos --  Find position of last occurrence of a char in a string  strspn --  Find length of initial segment matching mask  strstr  -- Find first occurrence of a string strtok -- Tokenize string strtolower  -- Make a string lowercase strtoupper -- Make a string uppercase str_replace  --  Replace all occurrences of the search string with the replacement string
strtr -- Translate certain characters substr  -- Return part of a string substr_count -- Count the number of substring occurrences substr_replace -- Replace text within a portion of a string trim --  Strip whitespace from the beginning and end of a string  ucfirst -- Make a string's first character uppercase ucwords --  Uppercase the first character of each word in a string  vprintf -- Output a formatted string vsprintf -- Return a formatted string wordwrap --  Wraps a string to a given number of characters using a string break character.  nl_langinfo --  Query language and locale information
Arrays An array in PHP is  a structure which maps  keys  (array element names) to  values   The keys can specified explicitly or they can be omitted If keys are omited, integers starting with 0 are keys The value mapped to a key can, itself, be an array, so we can have nested arrays
Specifying an array A special function is used to specify arrays array( ) Format of Usage array( [key =>] value , … ) A key is either a string or a non-negative integer A value can be anything
Specifying an array (contd.) Format of associative array specification $ages = array(&quot;Peter&quot;=>32, &quot;Quagmire&quot;=>30, &quot;Joe&quot;=>34);  Here is another associative (hash) array: $ages['Peter'] = &quot;32&quot;;  $ages['Quagmire'] = &quot;30&quot;;  $ages['Joe'] = &quot;34&quot;;  Implicit indices are integers, starting at  0 Here is an ordinary array (indexed by integers, starting at 0): $ place s =  array (“ Cork”, “Dublin”, “Galway” ); Here is the same array written differently $places[0] = “Cork”; $places[1] = “Dublin”; $places[2] = “Galway”;
Specifying an array (contd.) If an explicit integer index is followed by implicit indices, they follow on from the highest previous index Here is an array indexed by integers 1, 2, 3 $ place s = array ( 1 =>  “ Cork”, “Dublin”, “Galway” ); Here is an array indexed by integers 1, 5, 6 $ place s = array ( 5=>  “ Cork”, 1 => “Dublin”, “Galway” );
Specifying an array (contd.) A two-dimensional hash array $ parent s = array (   “ tom” => array (“father”  => “bill”, “mother”=>”mary”), “dave” => array(“father”  => “tom”, “mother” => orla”) ); echo &quot;Is &quot; . $parents['tom']['father'] . &quot; a part of the family?&quot;; = bill A two-dimensional ordinary array $ heights  = array (   array (10,20,30,40,50), array(100,200) ); echo $heights[0][1] ; = 20 echo $heights[1][1] ; = 200
Array Example 1 <html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php  $capital = array ('France'=>'Paris','Ireland'=>'Dublin'); echo 'The capital of Ireland is '; echo $capital['Ireland']; ?> </p> </body> </html>
 
Array Example 2 <html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php  $capital = array ('France'=>'Paris',   ‘ Ireland'=>'Dublin'); echo &quot;The various capitals are\n<ul>&quot;; foreach ($capital as $city) { echo &quot;<li>$city</li>&quot;; }; echo &quot;</ul>&quot; ?> </p> </body> </html>
 
Array Example 3 <html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php $capital = array ('France'=>'Paris',   'Ireland'=>'Dublin'); echo &quot;The various capitals are\n<ul>&quot;; foreach ($capital as $country => $city)  { echo &quot;<li>The capital of $country is $city</li>&quot;; }; echo &quot;</ul>&quot; ?> </p> </body> </html>
 
Array Example 4 <html> <head> <title>Details about Fred</title> </head> <body> <h1>Details about Fred</h1> <?php $ages = array (&quot;Fred&quot; => 2, &quot;Tom&quot;=> 45); $parents = array (&quot;Fred&quot; => array(&quot;father&quot; => &quot;Tom&quot;, &quot;mother&quot;=>&quot;Mary&quot;)); print &quot;<p> Fred's age is &quot;; print  $ages[&quot;Fred&quot;] ; print &quot;.</p>&quot;; print &quot;<p>His father is &quot;; print  $parents[&quot;Fred&quot;][&quot;father&quot;] ; print &quot;.</p>&quot;; ?> </body> </html>
 
Array-manupulation functions PHP provides a huge set of array-manipulation functions array  --  Create an array  array_change_key_case  -- Returns an array with all string keys lowercased or uppercased array_chunk -- Split an array into chunks array_count_values -- Counts all the values of an array array_diff -- Computes the difference of arrays array_filter --  Filters elements of an array using a callback function  array_flip -- Flip all the values of an array array_fill -- Fill an array with values array_intersect  -- Computes the intersection of arrays array_key_exists  -- Checks if the given key or index exists in the array array_keys  -- Return all the keys of an array array_map --  Applies the callback to the elements of the given arrays  array_merge  -- Merge two or more arrays array_merge_recursive  -- Merge two or more arrays recursively array_multisort  -- Sort multiple or multi-dimensional arrays array_pad --  Pad array to the specified length with a value
array_pop -- Pop the element off the end of array array_push --  Push one or more elements onto the end of array  array_rand --  Pick one or more random entries out of an array  array_reverse --  Return an array with elements in reverse order  array_reduce --  Iteratively reduce the array to a single value using a callback function  array_shift --  Shift an element off the beginning of array  array_slice  -- Extract a slice of the array array_splice --  Remove a portion of the array and replace it with something else  array_sum --  Calculate the sum of values in an array.  array_unique -- Removes duplicate values from an array array_unshift --  Prepend one or more elements to the beginning of array  array_values -- Return all the values of an array array_walk --  Apply a user function to every member of an array  arsort  --  Sort an array in reverse order and maintain index association  asort  -- Sort an array and maintain index association compact --  Create array containing variables and their values  count  -- Count elements in a variable current -- Return the current element in an array
each  --  Return the current key and value pair from an array and advance the array cursor  end --  Set the internal pointer of an array to its last element  extract --  Import variables into the current symbol table from an array  in_array  -- Return TRUE if a value exists in an array array_search  --  Searches the array for a given value and returns the corresponding key if successful  key  -- Fetch a key from an associative array krsort  -- Sort an array by key in reverse order ksort  -- Sort an array by key list --  Assign variables as if they were an array  natsort --  Sort an array using a &quot;natural order&quot; algorithm  natcasesort --  Sort an array using a case insensitive &quot;natural order&quot; algorithm  next --  Advance the internal array pointer of an array  pos -- Get the current element from an array prev -- Rewind the internal array pointer range --  Create an array containing a range of elements  reset --  Set the internal pointer of an array to its first element
rsort  -- Sort an array in reverse order shuffle -- Shuffle an array sizeof  -- Get the number of elements in variable sort  -- Sort an array uasort  --  Sort an array with a user-defined comparison function and maintain index association  uksort  --  Sort an array by keys using a user-defined comparison function  usort  --  Sort an array by values using a user-defined comparison function
Objects and functions PHP supports object-oriented programming <?php class  thingAMeBob { function  say _ hello ()  {echo “ Hello, World! &quot;;} } $ thing1  = new  thingAMeBob ; $ thing1 -> say_hello (); ?> And functions <?php  function add($x,$y)  { $total = $x + $y;  return $total; } echo &quot;1 + 16 = &quot; . add(1,16);  ?>
The NULL data type This data type contains only one value NULL It is case-insensitive This is a value which is returned when some expression has no value Example $capital = array ('France'=>'Paris',   'Ireland'=>'Dublin'); $capitalOfEngland = $capital[‘England’]; In this case,  $capitalOfEngland  would get the value  NULL
Automatic variables in PHP One of the main benefits of PHP is that it provides lots of variables automatically Consider, for example, the .php file on the next slide It produces the output on the following two slides when viewed by MSIE 6.0 and Netscape 2.0
Example usage of automatic PHP variable <html> <head> <title>Your browser</title> </head> <body> <h1>Your Browser</h1> <p> You are using  <?php   echo $_ENV[HTTP_USER_AGENT];   ?> to view this page. </p> </body> </html>
 
 
Global arrays PHP creates 6 global arrays that contain EGPCS (environment, get, post, cookies and server) information PHP also creates a variable called $_REQUEST that contains all the information in the 6 global arrays PHP also creates a variable called $PHP_SELF that contains the name of the current script (relative to the doc root)
Global arrays $_ENV – Contains the values of any environment variables, such as the browser version Eg:  $_ENV[HTTP_USER_AGENT] $_POST – The values of any variables posted to the request.  Eg: $_POST[username] $_GET – The values of any variables sent via the URL Eg: $_GET[username]
Global arrays $_FILES – Contains information about any files submitted $_COOKIES – Contains any cookies submitted as name value pairs (see later lectures) $_SERVER – Contains useful information about the webserver
$_SERVER Keys [DOCUMENT_ROOT] [HTTP_*] [PHP_SELF] [QUERY_STRING] [REMOTE_ADDR] [REQUEST_METHOD] [REQUEST_URI] [SCRIPT_FILENAME] [SCRIPT_NAME] [SERVER_NAME] [SERVER_PORT] [SERVER_PROTOCOL] [SERVER_SOFTWARE]  [COMSPEC] [GATEWAY_INTERFACE] [PATHEXT] [PATH] [REMOTE_PORT] [SERVER_ADDR] [SERVER_ADMIN] [SERVER_SIGNATURE] [SystemRoot] [WINDIR]
Changing Data Type PHP will, in some circumstances, change the type of a datum  For example, it will treat a string of digits as a number if it finds them in an arithmetic expression PHP also supports type casting <?php $myInteger = 12; $myFloat = 1.3; $result = $myFloat +  (float)  $myInteger; echo $result  ?>
Ad

More Related Content

What's hot (18)

String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Pooja B S
 
Iteration
IterationIteration
Iteration
Pooja B S
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data Types
Ravi Shankar
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Python
PythonPython
Python
Kumar Gaurav
 
Python ppt
Python pptPython ppt
Python ppt
Anush verma
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
Strings in python
Strings in pythonStrings in python
Strings in python
Prabhakaran V M
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
Luigi De Russis
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
S.M. Salaquzzaman
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
 
Python
PythonPython
Python
대갑 김
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Matt Harrison
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Python strings
Python stringsPython strings
Python strings
Mohammed Sikander
 
python codes
python codespython codes
python codes
tusharpanda88
 
String in python use of split method
String in python use of split methodString in python use of split method
String in python use of split method
vikram mahendra
 

Viewers also liked (6)

PHP-Part4
PHP-Part4PHP-Part4
PHP-Part4
Ahmed Saihood
 
List of all php array functions
List of all php array functionsList of all php array functions
List of all php array functions
Chetan Patel
 
PHP Regular Expressions
PHP Regular ExpressionsPHP Regular Expressions
PHP Regular Expressions
Jussi Pohjolainen
 
Form validation with built in functions
Form validation with built in functions Form validation with built in functions
Form validation with built in functions
Mudasir Syed
 
Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26
SynapseindiaComplaints
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
List of all php array functions
List of all php array functionsList of all php array functions
List of all php array functions
Chetan Patel
 
Form validation with built in functions
Form validation with built in functions Form validation with built in functions
Form validation with built in functions
Mudasir Syed
 
Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26
SynapseindiaComplaints
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
Ad

Similar to Variables In Php 1 (20)

Tokens in php (php: Hypertext Preprocessor).pptx
Tokens in  php (php: Hypertext Preprocessor).pptxTokens in  php (php: Hypertext Preprocessor).pptx
Tokens in php (php: Hypertext Preprocessor).pptx
BINJAD1
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
Muthuselvam RS
 
Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
UNIT II (7).pptx
UNIT II (7).pptxUNIT II (7).pptx
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPTCfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
Chapterabcdefghijklmnopqrdstuvwxydanniipo
ChapterabcdefghijklmnopqrdstuvwxydanniipoChapterabcdefghijklmnopqrdstuvwxydanniipo
Chapterabcdefghijklmnopqrdstuvwxydanniipo
abritip
 
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdfpython1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
rohithzach
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointer
Nishant Munjal
 
string function with example...................
string function with example...................string function with example...................
string function with example...................
NishantsrivastavaV
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
JamesChristianGadian
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
phanleson
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
adityakumawat625
 
Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Intoduction to php strings
baabtra.com - No. 1 supplier of quality freshers
 
Day5 String python language for btech.pptx
Day5 String python language for btech.pptxDay5 String python language for btech.pptx
Day5 String python language for btech.pptx
mrsam3062
 
Strings
StringsStrings
Strings
Mitali Chugh
 
Php
PhpPhp
Php
shakubar sathik
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
International Islamic University
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
Appili Vamsi Krishna
 
Tokens in php (php: Hypertext Preprocessor).pptx
Tokens in  php (php: Hypertext Preprocessor).pptxTokens in  php (php: Hypertext Preprocessor).pptx
Tokens in php (php: Hypertext Preprocessor).pptx
BINJAD1
 
Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPTCfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
Cfbcgdhfghdfhghggfhghghgfhgfhgfhhapter11.PPT
JITENDER773791
 
Chapterabcdefghijklmnopqrdstuvwxydanniipo
ChapterabcdefghijklmnopqrdstuvwxydanniipoChapterabcdefghijklmnopqrdstuvwxydanniipo
Chapterabcdefghijklmnopqrdstuvwxydanniipo
abritip
 
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdfpython1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
rohithzach
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointer
Nishant Munjal
 
string function with example...................
string function with example...................string function with example...................
string function with example...................
NishantsrivastavaV
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
JamesChristianGadian
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
phanleson
 
Day5 String python language for btech.pptx
Day5 String python language for btech.pptxDay5 String python language for btech.pptx
Day5 String python language for btech.pptx
mrsam3062
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
Appili Vamsi Krishna
 
Ad

More from Digital Insights - Digital Marketing Agency (20)

Diploma-GCD-ContentMarketing-Personas-Week2
Diploma-GCD-ContentMarketing-Personas-Week2Diploma-GCD-ContentMarketing-Personas-Week2
Diploma-GCD-ContentMarketing-Personas-Week2
Digital Insights - Digital Marketing Agency
 
DigitalInsights-DigitalMarketingStrategy&Planning
DigitalInsights-DigitalMarketingStrategy&PlanningDigitalInsights-DigitalMarketingStrategy&Planning
DigitalInsights-DigitalMarketingStrategy&Planning
Digital Insights - Digital Marketing Agency
 
DI-Facebook-DCEB-Session
DI-Facebook-DCEB-SessionDI-Facebook-DCEB-Session
DI-Facebook-DCEB-Session
Digital Insights - Digital Marketing Agency
 
DBS-Week2-DigitalStrategySession
DBS-Week2-DigitalStrategySessionDBS-Week2-DigitalStrategySession
DBS-Week2-DigitalStrategySession
Digital Insights - Digital Marketing Agency
 
GCD-Measurement&Analytics-Week11
GCD-Measurement&Analytics-Week11GCD-Measurement&Analytics-Week11
GCD-Measurement&Analytics-Week11
Digital Insights - Digital Marketing Agency
 
DBS-Week1-Introduction&OverviewDigitalMarketing
DBS-Week1-Introduction&OverviewDigitalMarketingDBS-Week1-Introduction&OverviewDigitalMarketing
DBS-Week1-Introduction&OverviewDigitalMarketing
Digital Insights - Digital Marketing Agency
 
DCEB-DigitalStrategySession-Jan24th
DCEB-DigitalStrategySession-Jan24thDCEB-DigitalStrategySession-Jan24th
DCEB-DigitalStrategySession-Jan24th
Digital Insights - Digital Marketing Agency
 
GCD-eCommcereCaseStudies
GCD-eCommcereCaseStudiesGCD-eCommcereCaseStudies
GCD-eCommcereCaseStudies
Digital Insights - Digital Marketing Agency
 
GCD-Week8-EmailMarketing
GCD-Week8-EmailMarketingGCD-Week8-EmailMarketing
GCD-Week8-EmailMarketing
Digital Insights - Digital Marketing Agency
 
GCD-Week7-SEO-Session
GCD-Week7-SEO-SessionGCD-Week7-SEO-Session
GCD-Week7-SEO-Session
Digital Insights - Digital Marketing Agency
 
Week12-DBS-ReviewAndPlanningSession
Week12-DBS-ReviewAndPlanningSessionWeek12-DBS-ReviewAndPlanningSession
Week12-DBS-ReviewAndPlanningSession
Digital Insights - Digital Marketing Agency
 
GCD-Week5-Facebook-LinkedIn-Ads
GCD-Week5-Facebook-LinkedIn-AdsGCD-Week5-Facebook-LinkedIn-Ads
GCD-Week5-Facebook-LinkedIn-Ads
Digital Insights - Digital Marketing Agency
 
DBS-Week11-Measurement&Analyics
DBS-Week11-Measurement&AnalyicsDBS-Week11-Measurement&Analyics
DBS-Week11-Measurement&Analyics
Digital Insights - Digital Marketing Agency
 
GCD-Week6-PPC-Ads-Session
GCD-Week6-PPC-Ads-SessionGCD-Week6-PPC-Ads-Session
GCD-Week6-PPC-Ads-Session
Digital Insights - Digital Marketing Agency
 
RPC-Wordpress-Session
RPC-Wordpress-SessionRPC-Wordpress-Session
RPC-Wordpress-Session
Digital Insights - Digital Marketing Agency
 
DBS-Week10-EcommSites&SalesFunnells
DBS-Week10-EcommSites&SalesFunnellsDBS-Week10-EcommSites&SalesFunnells
DBS-Week10-EcommSites&SalesFunnells
Digital Insights - Digital Marketing Agency
 
GCD-Week5-SocialMediaPlatforms
GCD-Week5-SocialMediaPlatformsGCD-Week5-SocialMediaPlatforms
GCD-Week5-SocialMediaPlatforms
Digital Insights - Digital Marketing Agency
 
DBS-Week3-B2C&B2B-ContentMarketing-Session
DBS-Week3-B2C&B2B-ContentMarketing-SessionDBS-Week3-B2C&B2B-ContentMarketing-Session
DBS-Week3-B2C&B2B-ContentMarketing-Session
Digital Insights - Digital Marketing Agency
 
ECM-PPC-Session
ECM-PPC-SessionECM-PPC-Session
ECM-PPC-Session
Digital Insights - Digital Marketing Agency
 
DBS-Week9-Wordpress-Session
DBS-Week9-Wordpress-SessionDBS-Week9-Wordpress-Session
DBS-Week9-Wordpress-Session
Digital Insights - Digital Marketing Agency
 

Recently uploaded (20)

Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
TrsLabs - Leverage the Power of UPI Payments
TrsLabs - Leverage the Power of UPI PaymentsTrsLabs - Leverage the Power of UPI Payments
TrsLabs - Leverage the Power of UPI Payments
Trs Labs
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Make GenAI investments go further with the Dell AI Factory
Make GenAI investments go further with the Dell AI FactoryMake GenAI investments go further with the Dell AI Factory
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Vibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdfVibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdf
Baiju Muthukadan
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Build 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHSBuild 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHS
TECH EHS Solution
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
TrsLabs - Leverage the Power of UPI Payments
TrsLabs - Leverage the Power of UPI PaymentsTrsLabs - Leverage the Power of UPI Payments
TrsLabs - Leverage the Power of UPI Payments
Trs Labs
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Make GenAI investments go further with the Dell AI Factory
Make GenAI investments go further with the Dell AI FactoryMake GenAI investments go further with the Dell AI Factory
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Vibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdfVibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdf
Baiju Muthukadan
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Build 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHSBuild 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHS
TECH EHS Solution
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 

Variables In Php 1

  • 2. Variables in PHP Variables in PHP are denoted by a dollar sign followed by the name of the variable. A variable name is case-sensitive. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
  • 3. Example Usage of Variables <html> <head> <title>Greetings</title> </head> <body> <h1>Greetings</h1> <p> <?php $person = &quot;Tom&quot;; $Person = &quot;Dick&quot;; echo &quot;Hello $person and $Person &quot;; ?> </p> </body> </html>
  • 4.  
  • 5. Data Types in PHP PHP supports eight primitive data types There are four scalar types boolean integer floating-point number string There are two structured types array object There are two special data types resource NULL The programmer does not specify the type of a variable a variable’s type is determined from the context of its usage
  • 6. Booleans The boolean data type admits two values true (case-insensitive) false (case-insensitive) Example usage $itIsRainingToday = true; $thePrinterIsBusy = True; $theQueueIsEmpty = FALSE;
  • 7. Integers Integers can be specified in decimal, hexadecimal or octal notation, optionally preceded by a sign In octal notation, the number must have a leading 0 In hexadecimal notation , the number must have a leading 0x. Example s $a = 1234 ; # decimal number $a = -123 ; # a negative number $a = 0123 ; # octal number (equivalent to 83 decimal) $a = 0x1 B ; # hexadecimal number (equivalent to 2 7 decimal) The maximum size of an integer is platform-dependent, but usually it’s 32 bits signed – about 2,000,000,000 PHP does not support unsigned integers.
  • 8. Floating Point Numbers These can be specified using any of these forms : $a = 1.234; $a = 1.2e3; $a = 7E-10; The maximum size of a float is platform-dependent, although most support a maximum of about 1.8e308 with a precision of roughly 14 decimal digits
  • 9. Strings A string literal can be specified in three different ways : single quoted double quoted heredoc syntax
  • 10. Double-quoted Strings In double-quoted strings, variables are interpreted to their values, and various characters can be escaped \n linefeed \r carriage return \t horizontal tab \\ backslash \$ dollar sign \” double quote \[0-7]{1,3} a character in octal notation \x[0-9A-Fa-f]{1,2} a character in hexadecimal notation
  • 11. Single-quoted Strings In single-quoted strings, single-quotes and backslashes must be escaped with a preceding backslash Example usage echo 'this is a simple string'; echo 'You c an embed newlines in strings, just like this .'; echo ‘ Douglas MacArthur said &quot;I\'ll be back ” when leaving the Phillipines '; echo 'Are you sure you want to delete C:\\*.*?';
  • 12. Heredoc Strings Heredoc strings are like double-quoted strings without the double quotes A heredoc string is delimited as follows The string is preceded by <<< followed by a label The string followed by a 2 nd occurrence of the same label Example usage $str = <<<EOD Example of string spanning multiple lines using heredoc syntax. EOD ;
  • 13. String-manipulation functions PHP provides huge range of string-manipulation functions: addcslashes -- Quote string with slashes in a C style addslashes -- Quote string with slashes bin2hex -- Convert binary data into hexadecimal representation chop -- Alias of rtrim() chr -- Return a specific character chunk_split -- Split a string into smaller chunks convert_cyr_string -- Convert from one Cyrillic character set to another count_chars -- Return information about characters used in a string crc32 -- Calculates the crc32 polynomial of a string crypt -- One-way string encryption (hashing) echo -- Output one or more strings explode -- Split a string into an array get_html_translation_table -- Returns the translation table used by htmlspecialchars() and htmlentities()
  • 14. get_meta_tags -- Extracts all meta tag content attributes from a file and returns an array hebrev -- Convert logical Hebrew text to visual text hebrevc -- Convert logical Hebrew text to visual text with newline conversion htmlentities -- Convert all applicable characters to HTML entities htmlspecialchars -- Convert special characters to HTML entities implode – creates a string from array elements join -- Join array elements with a string levenshtein -- Calculate Levenshtein distance between two strings localeconv -- Get numeric formatting information ltrim -- Strip whitespace from the beginning of a string md5 -- Calculate the md5 hash of a string md5_file -- Calculates the md5 hash of a given filename metaphone -- Calculate the metaphone key of a string nl2br -- Inserts HTML line breaks before all newlines in a string ord -- Return ASCII value of character parse_str -- Parses the string into variables print -- Output a string printf -- Output a formatted string
  • 15. quoted_printable_decode -- Convert a quoted-printable string to an 8 bit string quotemeta -- Quote meta characters str_rot13 -- Perform the rot13 transform on a string rtrim -- Strip whitespace from the end of a string sscanf -- Parses input from a string according to a format setlocale -- Set locale information similar_text -- Calculate the similarity between two strings soundex -- Calculate the soundex key of a string sprintf -- Return a formatted string strncasecmp -- Binary safe case-insensitive string comparison of the first n characters strcasecmp -- Binary safe case-insensitive string comparison strchr -- Find the first occurrence of a character strcmp -- Binary safe string comparison strcoll -- Locale based string comparison strcspn -- Find length of initial segment not matching mask strip_tags -- Strip HTML and PHP tags from a string stripcslashes -- Un-quote string quoted with addcslashes() stripslashes -- Un-quote string quoted with addslashes()
  • 16. stristr -- Case-insensitive strstr() strlen -- Get string length strnatcmp -- String comparisons using a &quot;natural order&quot; algorithm strnatcasecmp -- Case insensitive string comparisons using a &quot;natural order&quot; algorithm strncmp -- Binary safe string comparison of the first n characters str_pad -- Pad a string to a certain length with another string strpos -- Find position of first occurrence of a string strrchr -- Find the last occurrence of a character in a string str_repeat -- Repeat a string strrev -- Reverse a string strrpos -- Find position of last occurrence of a char in a string strspn -- Find length of initial segment matching mask strstr -- Find first occurrence of a string strtok -- Tokenize string strtolower -- Make a string lowercase strtoupper -- Make a string uppercase str_replace -- Replace all occurrences of the search string with the replacement string
  • 17. strtr -- Translate certain characters substr -- Return part of a string substr_count -- Count the number of substring occurrences substr_replace -- Replace text within a portion of a string trim -- Strip whitespace from the beginning and end of a string ucfirst -- Make a string's first character uppercase ucwords -- Uppercase the first character of each word in a string vprintf -- Output a formatted string vsprintf -- Return a formatted string wordwrap -- Wraps a string to a given number of characters using a string break character. nl_langinfo -- Query language and locale information
  • 18. Arrays An array in PHP is a structure which maps keys (array element names) to values The keys can specified explicitly or they can be omitted If keys are omited, integers starting with 0 are keys The value mapped to a key can, itself, be an array, so we can have nested arrays
  • 19. Specifying an array A special function is used to specify arrays array( ) Format of Usage array( [key =>] value , … ) A key is either a string or a non-negative integer A value can be anything
  • 20. Specifying an array (contd.) Format of associative array specification $ages = array(&quot;Peter&quot;=>32, &quot;Quagmire&quot;=>30, &quot;Joe&quot;=>34); Here is another associative (hash) array: $ages['Peter'] = &quot;32&quot;; $ages['Quagmire'] = &quot;30&quot;; $ages['Joe'] = &quot;34&quot;; Implicit indices are integers, starting at 0 Here is an ordinary array (indexed by integers, starting at 0): $ place s = array (“ Cork”, “Dublin”, “Galway” ); Here is the same array written differently $places[0] = “Cork”; $places[1] = “Dublin”; $places[2] = “Galway”;
  • 21. Specifying an array (contd.) If an explicit integer index is followed by implicit indices, they follow on from the highest previous index Here is an array indexed by integers 1, 2, 3 $ place s = array ( 1 => “ Cork”, “Dublin”, “Galway” ); Here is an array indexed by integers 1, 5, 6 $ place s = array ( 5=> “ Cork”, 1 => “Dublin”, “Galway” );
  • 22. Specifying an array (contd.) A two-dimensional hash array $ parent s = array ( “ tom” => array (“father” => “bill”, “mother”=>”mary”), “dave” => array(“father” => “tom”, “mother” => orla”) ); echo &quot;Is &quot; . $parents['tom']['father'] . &quot; a part of the family?&quot;; = bill A two-dimensional ordinary array $ heights = array ( array (10,20,30,40,50), array(100,200) ); echo $heights[0][1] ; = 20 echo $heights[1][1] ; = 200
  • 23. Array Example 1 <html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php $capital = array ('France'=>'Paris','Ireland'=>'Dublin'); echo 'The capital of Ireland is '; echo $capital['Ireland']; ?> </p> </body> </html>
  • 24.  
  • 25. Array Example 2 <html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php $capital = array ('France'=>'Paris', ‘ Ireland'=>'Dublin'); echo &quot;The various capitals are\n<ul>&quot;; foreach ($capital as $city) { echo &quot;<li>$city</li>&quot;; }; echo &quot;</ul>&quot; ?> </p> </body> </html>
  • 26.  
  • 27. Array Example 3 <html> <head><title>Array Demo</title></head> <body> <h1>Array Demo</h1> <p> <?php $capital = array ('France'=>'Paris', 'Ireland'=>'Dublin'); echo &quot;The various capitals are\n<ul>&quot;; foreach ($capital as $country => $city) { echo &quot;<li>The capital of $country is $city</li>&quot;; }; echo &quot;</ul>&quot; ?> </p> </body> </html>
  • 28.  
  • 29. Array Example 4 <html> <head> <title>Details about Fred</title> </head> <body> <h1>Details about Fred</h1> <?php $ages = array (&quot;Fred&quot; => 2, &quot;Tom&quot;=> 45); $parents = array (&quot;Fred&quot; => array(&quot;father&quot; => &quot;Tom&quot;, &quot;mother&quot;=>&quot;Mary&quot;)); print &quot;<p> Fred's age is &quot;; print $ages[&quot;Fred&quot;] ; print &quot;.</p>&quot;; print &quot;<p>His father is &quot;; print $parents[&quot;Fred&quot;][&quot;father&quot;] ; print &quot;.</p>&quot;; ?> </body> </html>
  • 30.  
  • 31. Array-manupulation functions PHP provides a huge set of array-manipulation functions array -- Create an array array_change_key_case -- Returns an array with all string keys lowercased or uppercased array_chunk -- Split an array into chunks array_count_values -- Counts all the values of an array array_diff -- Computes the difference of arrays array_filter -- Filters elements of an array using a callback function array_flip -- Flip all the values of an array array_fill -- Fill an array with values array_intersect -- Computes the intersection of arrays array_key_exists -- Checks if the given key or index exists in the array array_keys -- Return all the keys of an array array_map -- Applies the callback to the elements of the given arrays array_merge -- Merge two or more arrays array_merge_recursive -- Merge two or more arrays recursively array_multisort -- Sort multiple or multi-dimensional arrays array_pad -- Pad array to the specified length with a value
  • 32. array_pop -- Pop the element off the end of array array_push -- Push one or more elements onto the end of array array_rand -- Pick one or more random entries out of an array array_reverse -- Return an array with elements in reverse order array_reduce -- Iteratively reduce the array to a single value using a callback function array_shift -- Shift an element off the beginning of array array_slice -- Extract a slice of the array array_splice -- Remove a portion of the array and replace it with something else array_sum -- Calculate the sum of values in an array. array_unique -- Removes duplicate values from an array array_unshift -- Prepend one or more elements to the beginning of array array_values -- Return all the values of an array array_walk -- Apply a user function to every member of an array arsort -- Sort an array in reverse order and maintain index association asort -- Sort an array and maintain index association compact -- Create array containing variables and their values count -- Count elements in a variable current -- Return the current element in an array
  • 33. each -- Return the current key and value pair from an array and advance the array cursor end -- Set the internal pointer of an array to its last element extract -- Import variables into the current symbol table from an array in_array -- Return TRUE if a value exists in an array array_search -- Searches the array for a given value and returns the corresponding key if successful key -- Fetch a key from an associative array krsort -- Sort an array by key in reverse order ksort -- Sort an array by key list -- Assign variables as if they were an array natsort -- Sort an array using a &quot;natural order&quot; algorithm natcasesort -- Sort an array using a case insensitive &quot;natural order&quot; algorithm next -- Advance the internal array pointer of an array pos -- Get the current element from an array prev -- Rewind the internal array pointer range -- Create an array containing a range of elements reset -- Set the internal pointer of an array to its first element
  • 34. rsort -- Sort an array in reverse order shuffle -- Shuffle an array sizeof -- Get the number of elements in variable sort -- Sort an array uasort -- Sort an array with a user-defined comparison function and maintain index association uksort -- Sort an array by keys using a user-defined comparison function usort -- Sort an array by values using a user-defined comparison function
  • 35. Objects and functions PHP supports object-oriented programming <?php class thingAMeBob { function say _ hello () {echo “ Hello, World! &quot;;} } $ thing1 = new thingAMeBob ; $ thing1 -> say_hello (); ?> And functions <?php function add($x,$y) { $total = $x + $y; return $total; } echo &quot;1 + 16 = &quot; . add(1,16); ?>
  • 36. The NULL data type This data type contains only one value NULL It is case-insensitive This is a value which is returned when some expression has no value Example $capital = array ('France'=>'Paris', 'Ireland'=>'Dublin'); $capitalOfEngland = $capital[‘England’]; In this case, $capitalOfEngland would get the value NULL
  • 37. Automatic variables in PHP One of the main benefits of PHP is that it provides lots of variables automatically Consider, for example, the .php file on the next slide It produces the output on the following two slides when viewed by MSIE 6.0 and Netscape 2.0
  • 38. Example usage of automatic PHP variable <html> <head> <title>Your browser</title> </head> <body> <h1>Your Browser</h1> <p> You are using <?php echo $_ENV[HTTP_USER_AGENT]; ?> to view this page. </p> </body> </html>
  • 39.  
  • 40.  
  • 41. Global arrays PHP creates 6 global arrays that contain EGPCS (environment, get, post, cookies and server) information PHP also creates a variable called $_REQUEST that contains all the information in the 6 global arrays PHP also creates a variable called $PHP_SELF that contains the name of the current script (relative to the doc root)
  • 42. Global arrays $_ENV – Contains the values of any environment variables, such as the browser version Eg: $_ENV[HTTP_USER_AGENT] $_POST – The values of any variables posted to the request. Eg: $_POST[username] $_GET – The values of any variables sent via the URL Eg: $_GET[username]
  • 43. Global arrays $_FILES – Contains information about any files submitted $_COOKIES – Contains any cookies submitted as name value pairs (see later lectures) $_SERVER – Contains useful information about the webserver
  • 44. $_SERVER Keys [DOCUMENT_ROOT] [HTTP_*] [PHP_SELF] [QUERY_STRING] [REMOTE_ADDR] [REQUEST_METHOD] [REQUEST_URI] [SCRIPT_FILENAME] [SCRIPT_NAME] [SERVER_NAME] [SERVER_PORT] [SERVER_PROTOCOL] [SERVER_SOFTWARE] [COMSPEC] [GATEWAY_INTERFACE] [PATHEXT] [PATH] [REMOTE_PORT] [SERVER_ADDR] [SERVER_ADMIN] [SERVER_SIGNATURE] [SystemRoot] [WINDIR]
  • 45. Changing Data Type PHP will, in some circumstances, change the type of a datum For example, it will treat a string of digits as a number if it finds them in an arithmetic expression PHP also supports type casting <?php $myInteger = 12; $myFloat = 1.3; $result = $myFloat + (float) $myInteger; echo $result ?>