Introduction to php functions and arrays - PowerPoint PPT Presentation

About This Presentation
Title:

Introduction to php functions and arrays

Description:

Learn what are php functions, how functions arguments work, what are optional parameters? What are default arguments, How to create functions with in functions? what are arrays, what are built in array functions? what are super globals? – PowerPoint PPT presentation

Number of Views:1211

less

Transcript and Presenter's Notes

Title: Introduction to php functions and arrays


1
By ProgrammerBlog.net
http//programmerblog.net/
http//programmerblog.net Introduction to
Functions and Arrays
2
PHP Fundamentals Functions
By ProgrammerBlog.net
http//programmerblog.net/
  • A set of constructs which allow the programmer to
    break up their code into smaller, more
    manageable, chunks which can be called by name
    and which may or may not return a value.
  • function function_name (parameters)
  • function-body
  • function helloWorld()
  • echo "HelloWorld" //No out put is
    shown

3
Functions Passing Parameters
By ProgrammerBlog.net
http//programmerblog.net/
  • Passing parameters by value
  • function salestax(price,tax)
  • total price (price tax
  • echo "Total cost total"
  • salestax(15.00,.075)
  • pricetag 15.00
  • salestax .075
  • salestax(pricetag, salestax)

4
Functions Passing Parameters
By ProgrammerBlog.net
http//programmerblog.net/
  • Passing parameters by reference
  • cost 20.00
  • tax 0.05
  • function calculate_cost(cost, tax)
  • // Modify the cost variable
  • cost cost (cost tax)
  • // Perform some random change to the tax
    variable.
  • tax 4
  • calculate_cost(cost,tax)
  • echo "Tax is ". tax100."ltbr /gt"
  • echo "Cost is ". cost."ltbr /gt"

5
By ProgrammerBlog.net
http//programmerblog.net/
Functions Default Argument Values
  • Default values are automatically assigned to the
    argument if no other value is provided
  • function salestax(price,tax.0575)
  • total price (price tax)
  • echo "Total cost total"
  • price 15.47
  • salestax(price)

6
By ProgrammerBlog.net
http//programmerblog.net/
Functions Optional Arguments
  • Certain arguments can be designated as optional
    by placing them at the end of the list and
    assigning them a default value of nothing .
  • function salestax(price, tax"")
  • total price (price tax)
  • echo "Total cost total"
  • salestax(42.00)
  • function calculate(price,price2"",price3
    "")
  • echo price price2 price3
  • calculate(10,"", 3)

7
By ProgrammerBlog.net
http//programmerblog.net/
Functions Returning Values from a Function
  • You can pass data back to the caller by way of
    the return keyword.
  • function salestax(price,tax.0575)
  • total price (price tax)
  • return total
  • total salestax(6.50)
  • Returning Multiple Values
  • function retrieve_user_profile()
  • user "Jason"
  • user "jason_at_example.com"
  • return user
  • list(name,email) retrieve_user_profile()
  • echo "Name name, email email "

8
By ProgrammerBlog.net
http//programmerblog.net/
Functions Nesting Functions
  • defining and invoking functions within
    functions
  • function salestax(price,tax)
  • function convert_pound(dollars,
    conversion1.6)
  • return dollars conversion
  • total price (price tax)
  • echo "Total cost in dollars total.
    Cost in British pounds "
  • . convert_pound(total)
  • salestax(15.00,.075)
  • echo convert_pound(15)

9
Functions Recursive Functions
By ProgrammerBlog.net
http//programmerblog.net/
functions that call themselves function
nfact(n) if (n 0)
return 1 else
return n nfact(n - 1)
//call to function nfact(num)
10
Functions Variable Functions
By ProgrammerBlog.net
http//programmerblog.net/
  • Functions with parameters on run time
  • function hello()
  • if (func_num_args()gt0)
  • argfunc_get_arg(0) //Thefirstargumentisatposi
    tion0
  • echo "Helloarg"
  • else
  • echo "HelloWorld"
  • hello("Reader") //Displays"HelloReader"
  • hello() //Displays"HelloWorld"

11
By ProgrammerBlog.net
http//programmerblog.net/
Server Side Includes (SSI) include() function
  • Include function
  • You can insert the content of one PHP file into
    another PHP file before the server executes it,
    with the include() or require() function. (e.g.
    Header, Menu, footer)
  • The include() function takes all the content in a
    specified file and includes it in the current
    file
  • include() generates a warning, but the script
    will continue execution
  • lthtmlgt
  • ltbodygt
  • lt?php include("header.php") ?gt
  • lth1gtWelcome to my home page!lt/h1gt
  • ltpgtSome text.lt/pgt
  • lt/bodygt
  • lt/htmlgt

12
By ProgrammerBlog.net
http//programmerblog.net/
Server Side Includes (SSI) include() function
  • lthtmlgt
  • ltbodygt
  • ltdiv class"leftmenu"gt
  • lt?php include("menu.php") ?gt
  • lt/divgt
  • lth1gtWelcome to my home page.lt/h1gt
  • ltpgtSome text.lt/pgt
  • lt/bodygt
  • lt/htmlgt

13
By ProgrammerBlog.net
http//programmerblog.net/
Server Side Includes (SSI) include() function
lthtmlgt ltbodygt ltdiv class"leftmenu"gt lta
href"/default.php"gtHomelt/agt lta
href"/tutorials.php"gtTutorialslt/agt lta
href"/references.php"gtReferenceslt/agt lta
href"/examples.php"gtExampleslt/agt lta
href"/about.php"gtAbout Uslt/agt lta
href"/contact.php"gtContact Uslt/agt lt/divgt lth1gtWelc
ome to my home page!lt/h1gt ltpgtSome
text.lt/pgt lt/bodygt lt/htmlgt
14
By ProgrammerBlog.net
http//programmerblog.net/
Server Side Includes (SSI) require() function
  • Require function
  • require() generates a fatal error, and
    the script will stop
  • include() generates a warning, but the script
    will continue execution
  • lthtmlgt
  • ltbodygt
  • lt?php
  • require("wrongFile.php")
  • echo "Hello World!"
  • ?gt
  • lt/bodygt
  • lt/htmlgt
  • It is recommended to use the require() function
    instead of include(), because scripts should not
    continue after an error.

15
PHP Built In Functions
By ProgrammerBlog.net
http//programmerblog.net/
  • Math functions
  • http//www.w3schools.com/php/php_ref_math.asp
  • pi() Returns the value of PI
  • pow() Returns the value of x to the power of y
  • rad2deg() Converts a radian number to a degree
  • rand() Returns a random integer
  • round() Rounds a number to the nearest integer
  • sin() Returns the sine of a number
  • sinh() Returns the hyperbolic sine of a number
  • sqrt() Returns the square root of a number
  • srand() Seeds the random number generator
  • tan() Returns the tangent of an angle
  • tanh()
  • abs() Returns the absolute value of a number

16
PHP Built In Misc. Functions
By ProgrammerBlog.net
http//programmerblog.net/
  • Constants
  • M_LN10 Returns the natural logarithm of 10
    (approx. 2.302)
  • M_PI Returns PI (approx. 3.14159)
  • M_SQRT2 Returns the square root of 2 (approx.
    1.414)
  • Miscellaneous Functions
  • Strlen Returns length of a string
  • count() Returns the count of an array.
  • Strtolower strtolower() to lower
    case.
  • strtoupper() strtoupper() convert
    string to upper case

17
PHP Fundaments - Arrays
By ProgrammerBlog.net
http//programmerblog.net/
  • Arrays are ordered collections of items, called
    elements
  • Each element has a value, and is identified by a
    key that is unique to the array It belongs to
  • In PHP, there are three kind of arrays
  • Numeric array - An array with a
    numeric index
  • Associative array - An array where each
    ID key is associated with a value
  • Multidimensional array - An array containing one
    or more arrays.
  • a array()
  • state0 "Delaware"
  • a array (10, 20, 30)
  • a array (a gt 10, b gt 20, cee gt 30)
  • a array (5 gt 1, 3 gt 2, 1 gt 3,)

18
PHP Fundaments - Arrays
By ProgrammerBlog.net
http//programmerblog.net/
  • Numeric Arrays
  • A numeric array stores each array element with a
    numeric index.
  • cars array("Saab","Volvo","BMW","Toyota")
  • cars0"Saab" //2nd way of declaring
    arrays
  • cars1"Volvo"
  • cars2"BMW"
  • cars3"Toyota"
  • echo cars0 . " and " . cars1 . " are
    Swedish cars."
  • Associative Arrays
  • An associative array, each ID key is associated
    with a value.
  • ages array(John"gt32, Jane"gt30,
    David"gt34)
  • agesJohn ' "32"
  • agesJane ' "30"
  • agesDavid ' "34"
  • states array (0 gt "Alabama", "1" gt
    "Alaska"..."49" gt "Wyoming") //numeric
  • states array ("OH" gt "Ohio", "PA" gt
    "Pennsylvania", "NY" gt "New York")

19
PHP Fundaments - Arrays
By ProgrammerBlog.net
http//programmerblog.net/
  • Multidimensional Arrays
  • Arrays of arrays, known as multidimensional
    arrays
  • In a multidimensional array, each element in the
    main array can also be an array.
  • cars array ( Toyota"gtarray ( Corolla, "
    Camry, "Toyota 4Runner ),
  • Suzuki"gtarray ( Vitara ),
  • Honda"gtarray ( "Accord, Sedan,
    Odyssey ) )
  • echo "Is " . cars Toyota '2 . " a member
    of the Toyota cars?
  • Is Toyota 4Runner a member of the Toyota cars?
  • states array (
  • "Ohio" gt array ("population" gt
    "11,353,140", "capital" gt "Columbus"),
  • "Nebraska" gt array ("population" gt
    "1,711,263", "capital" gt "Omaha")
  • )

20
PHP Fundaments Printing Arrays
By ProgrammerBlog.net
http//programmerblog.net/
  • print_r() and var_dump()
  • var_dump
  • var_dump() outputs the data types of each value
  • var_dump() is capable of outputting the value of
    more than one variable
  • var_dump(states)
  • a array (1, 2, 3)
  • b array (a gt 1, b gt 2, c gt 3)
  • var_dump (a b) // creates union of arrays
  • If 2 arrays have common elements and also share
    same string or numeric key will appearance in
    result or output
  • print_r
  • print_r can return its output as a string, as
    opposed to writing it to the scripts standard
    output
  • print_r(states)

21
By ProgrammerBlog.net
http//programmerblog.net/
PHP Fundaments Comparing - Counting Arrays
  • a array (1, 2, 3)
  • b array (1 gt 2, 2 gt 3, 0 gt 1)
  • c array (a gt 1, b gt 2, c gt
    3)
  • var_dump (a b) // True
  • var_dump (a b) // False
    returns true only if the array contains the

  • same key/value pairs in the same
    order
  • var_dump (a c) // True
  • var_dump (a c) // False
  • a array (1, 2, 4)
  • b array()
  • c 10
  • echo count (a) // Outputs 3
  • echo count (b) // Outputs 0
  • echo count (c) // Outputs 1
  • is_array() function echo in_array (a, 2) //
    True

22
By ProgrammerBlog.net
http//programmerblog.net/
By ProgrammerBlog.net
http//programmerblog.net/
PHP Fundaments Flipping and Reversing , Range
  • array_flip()
  • Exchanges all keys with their associated values
    in an array
  • trans  array("a" gt 1, "b" gt 1, "c" gt 2)tr
    ans  array_flip(trans)print_r(trans)
  • Output Array ( 1 gt b 2 gt c )
  • array_reverse()
  • Return an array with elements in reverse order
  • array_values()
  • array_values Return all the values of an array
  • array  array("size" gt "XL", "color" gt "gold")
    print_r(array_values(array))
  • array_keys Return all the keys of an array
  • range()
  • The range() function provides an easy way to
    quickly create and fill an array consisting of a
    range of low and high integer values.
  • die range(0,6) // Same as specifying
    die array(0,1,2,3,4,5,6)

23
PHP Fundaments Sorting Arrays
By ProgrammerBlog.net
http//programmerblog.net/
  • There are many functions in PHP core that provide
    various methods of sorting array contents.
  • sort
  • array array(a gt foo, b gt bar, c gt
    baz)
  • sort(array)
  • var_dump(array)
  • asort //to maintain key
    association,
  • - array array(a gt foo, b
    gt bar, c gt baz)
  • asort(array)
  • var_dump(array)
  • rsort,
  • arsort // sorting an array in
    descending order

24
By ProgrammerBlog.net
http//programmerblog.net/
PHP Fundaments Arrays as Stack and Queues
  • Stack Last in First Out.
  • array_push()
  • stack array()
  • array_push(stack, bar, baz)
  • var_dump(stack)
  • array_pop()
  • states array("Ohio","New York","California","Te
    xas")
  • state array_pop(states) // state "Texas"
  • Queues
  • array_shift, Shift an element off the beginning
    of array
  • array_unshift - Prepend one or more elements to
    the beginning of an array
  • stack array(qux, bar, baz)
  • first_element array_shift(stack)
  • var_dump(stack)
  • array_unshift(stack, foo)
  • var_dump(stack)

25
Super Globals
By ProgrammerBlog.net
http//programmerblog.net/
  • Several predefined variables in PHP are
    "superglobals", which means they are available in
    all scopes throughout a script. There is no need
    to do global variable to access them within
    functions or methods.
  • GLOBALS
  • _SERVER
  • _GET
  • _POST
  • _FILES
  • _COOKIE
  • _SESSION
  • _REQUEST
  • _ENV

26
Features Super Globals
By ProgrammerBlog.net
http//programmerblog.net/
  • GLOBALS References all variables available in
    global scope
  • lt?phpfunction test()     foo  "local variable
    "    echo 'foo in global scope ' . GLOBALS"
    foo" . "\n"    echo 'foo in current scope ' .
     foo . "\n"foo  "Example content"test()
    ?gt
  • _SERVER -- HTTP_SERVER_VARS deprecated
    Server and execution environment information
  • lt?phpecho _SERVER'SERVER_NAME'?gt

27
Super Globals
By ProgrammerBlog.net
http//programmerblog.net/
  • _ENV -- HTTP_ENV_VARS deprecated
    Environment variables
  • lt?phpecho 'My username is ' ._ENV"USER" . '!'
    ?gt
  • ip  _SERVER'REMOTE_ADDR'

28
Super Globals
By ProgrammerBlog.net
http//programmerblog.net/
  • Thank you for viewing this slide. Hope this is
    helpful for you.
  • please visit out blog
  • http//programmerblog.net
  • Follow us on twitter
  • https//twitter.com/progblogdotnet
Write a Comment
User Comments (0)
About PowerShow.com