0% found this document useful (0 votes)
35 views

PHP Arrays and Functions

This document discusses PHP arrays and functions. It covers the different types of arrays in PHP including indexed, associative, and multidimensional arrays. It provides examples of creating and accessing array elements using integer indices and keys/values. Various array functions are also described such as count(), is_array(), sort(), and print_r() for dumping arrays. The document then discusses defining custom functions in PHP including passing arguments by value and reference as well as variable scope. Local variables that exist only within a function are contrasted with global variables.

Uploaded by

Yousef Qasas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

PHP Arrays and Functions

This document discusses PHP arrays and functions. It covers the different types of arrays in PHP including indexed, associative, and multidimensional arrays. It provides examples of creating and accessing array elements using integer indices and keys/values. Various array functions are also described such as count(), is_array(), sort(), and print_r() for dumping arrays. The document then discusses defining custom functions in PHP including passing arguments by value and reference as well as variable scope. Local variables that exist only within a function are contrasted with global variables.

Uploaded by

Yousef Qasas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

PHP ARRAYS AND FUNCTIONS

ARRAY
 An array is a special variable, which can hold more
than one value at a time.
 In PHP, the array() is used to create an array:

array();
In PHP we have 3 types of arrays:
1. Indexed arrays - Arrays with a numeric index

2. Associative arrays - Arrays with named keys

3. Multidimensional arrays - Arrays containing one or


more arrays
INTEGER INDICES

<?php
$stuff = array("Hi", "There");
echo $stuff[1], "\n";
?>

There
INTEGER INDICES
<?php
$stuff = array();
$stuff[] = "Hello";
$stuff[] = "World";

echo $stuff[1], "\n";


?>
World
INTEGER INDICES
<?php
$stuff = array();
$stuff[2] = "Hello";
$stuff[9] = "World";

echo $stuff[9], "\n";


?>
World
KEY / VALUE
<?php
$stuff = array("name" => "Chuck",
"course" => "SI664");
echo $stuff["course"], "\n";
?>

SI664
DUMPING AN ARRAY
• The function print_r() dumps out PHP data - it is
used mostly for debugging
<?php
$stuff = array("name" =>
"Chuck",
"course"
=> "SI664");
print_r($stuff); Array
?> (
[name] => Chuck
[course] => SI664
)
DUMPING AN ARRAY
• The function print_r() dumps out PHP data - it is
used mostly for debugging
<?php
$stuff = array();
$stuff[2] = "Hello";
$stuff[9] = "World";
print_r($stuff);
?> Array
(
[2] => Chuck
[9] => SI664
)
VAR_DUMP .VS. PRINT_R
<?php
$stuff = array("name" => "Chuck",
"course" => "SI664");
var_dump($stuff);
?>
array(2) {
["name"]=>
string(5) "Chuck"
["course"]=>
string(5) "SI664"
}
http://stackoverflow.com/questions/3406171/php-var-dump-
vs-print-r
LOOPING THROUGH AN ARRAY
<?php
$stuff = array("name" =>
"Chuck",
"course" =>
“Web Design 2");
foreach($stuff as $k => $v
) {
echo "Key=",$k,"
Val=",$v,"\n";
}
?>
Key=name Val=Chuck
Key=course Val= Web Design 2
LOOPING THROUGH AN ARRAY
<?php
$colors= array(“red", “yellow",
“black");
$a_length = count($colors);

for($x = 0; $x < $a_length; $x++) {


echo $colors[$x]; red
echo "<br>"; yellow
}
?> black
ARRAYS OF ARRAYS
$majors = array
(
array("archtecural eng","computer eng","telecom eng"),
The elements of an array array("CIS","CS","SE"),
can be many things other array(" Accounting ","Marketing","Finance"),

than a string or integer. );


You can even have objects echo " In Engineering: ".$majors[0][0].", ".$majors[0][1].", and,
".$majors[0][2].".<br>";
or other arrays. echo " In IT : ".$majors[1][0].", ".$majors[1][1].", and
".$majors[1][2].".<br>";
echo " In administration sciences: ".$majors[2][0].",
".$majors[2][1].", and ".$majors[2][2].".<br>";

In Engineering: archtecural eng, computer eng, and, telecom eng.


In IT : CIS, CS, and SE.
In administration sciences: Accounting, Marketing, and Finance.
$course= array(
ARRAYS OF "IT" => array(
"Java" => "CIS",
ARRAYS "Sql" => "CS"),
"eng" => array(
"autocad"=>"Architectural
The elements of an array Eng",
can be many things other "Alg" => "Computer Eng")
than a string or integer. ) ;
You can even have objects echo $course["IT"]["Java"];

or other arrays.

CIS
ARRAY FUNCTIONS
• count($ar) - How many elements in an array
• is_array($ar) - Returns TRUE if a variable is an
array
• isset($ar['key']) - Returns TRUE if key is set in the
array
• sort($ar) - Sorts the array values (loses key)
• ksort($ar) - Sorts the array by key
• asort($ar) - Sorts array by value, keeping key
association
• shuffle($ar) - Shuffles the array into random order
$za = array(); Count: 2
$za["name"] = "Chuck"; $za Is an
$za["course"] = “WD2";
print "Count: " . count($za) . "\n";
array
if ( is_array($za) ) { name is
echo '$za Is an array' . "\n"; set
} addr is
else {
echo '$za Is not an array' .
not set
"\n";
}

echo isset($za['name']) ? "name is


set\n" : "name is not set\n";
echo isset($za['addr']) ? "addr is
set\n" : "addr is not set\n";
Array(
$za = array(); [name] => Chuck
$za["name"] = "Chuck"; [course] => WD2
$za["course"] = “WD2"; [topic] => PHP
$za["topic"] = "PHP"; )
print_r($za); Array(
sort($za); [0] => Chuck
print_r($za); [1] => PHP
[2] => WD2
)
Array(
[name] => Chuck
[course] => WD2
$za = array(); [topic] => PHP
$za["name"] = "Chuck"; )
$za["course"] = “WD2";
$za["topic"] = "PHP"; Array(
print_r($za); [course] => WD2
ksort($za); [name] => Chuck
print_r($za); [topic] => PHP
asort($za); )
print_r($za);
Array(
[name] => Chuck
[topic] => PHP
[course] => WD2
)
PHP ARRAY FUNCTIONS

 Visit the following website: http://php.net/. Then


explore the PHP arrays functions as shown in the
next slide.

in an array
what is the difference between:
empty() ,is_null() ,isset() unset()
FUNCTIONS?
• A function is a piece of code in a larger program. The
function performs a specific task.
• PHP has lots of built-in functions that we use all the time
• We write out own functions when our code reaches a
certain level of complexity.
• The advantages of using functions are:
Reducing duplication of code
Decomposing complex problems into simpler pieces.
Reuse of code
BUILT-IN FUNCTIONS...

• Much of the power of PHP comes from its built-in


functions

echo strrev(" .dlrow olleH");


echo str_repeat(“PHP", 2);
echo strtoupper(“web design!");
echo "\n";
Hello world.
PHP PHP
WEB DESIGN!
DEFINING YOUR OWN FUNCTIONS

• We use the function keyword to define a function, we


name the function and take optional argument variables.
The body of the function is in a block of code { }
function greet() {
print "Hello\n";
}
Hello
Hello
greet();
Hello
greet();
greet();
CALL BY VALUE
• The argument variable within the function is an "alias"
to the actual variable
• But even further, the alias is to a *copy* of the actual
variable in the function call
function double($alias) {
$alias = $alias * 2;
return $alias;
} Value = 10 Doubled = 20
$val = 10;
$dval = double($val);
echo "Value = $val Doubled =
$dval\n";
CALL BY REFERENCE

• Sometimes we want a function to change one of its


arguments - so we indicate that an argument is "by
reference" using ( & )
function
triple(&$realthing) {
$realthing = $realthing
* 3;
}

$val = 10;
triple($val); Triple = 30
echo "Triple = $val\n";
VARIABLE SCOPE
 In general, variable names used inside of function
code, do not mix with the variables outside of the
function. They are walled-off from the rest of the code.
This is done because you want to avoid "unexpected"
side effects if two programmers use the same variable
name in different parts of the code.
 We call this "name spacing" the variables. The
function variables are in one "name space" whilst the
main variables are in another "name space“
function try1() {
$val = 100;
LOCAL VARIABLES } Try1=
 Local variables are variables that are created within, and
10
$val = 10;
can be accessed only by, a function. try1();
 One set of local variables is the list of arguments to a echo "Try1 = $val\n";
function.

Global variables function try2() {


global $val;
 There are cases when you need a variable to have global $val = try2=
100; 100
scope: }
 because you want all your code to be able to access it.
$val = 10;
 To declare a variable as having global scope, use the try2();
keyword global. echo “try2= $val\n";
SUPERGLOBAL VARIABLES
 several predefined variables are available.
 These are known as superglobal variables,
 which means that they are provided by the PHP
environment
 but are global within the program, accessible
absolutely everywhere.
 These superglobals contain lots of useful information
about the currently running program and its
environment (see next table).
PHP $GLOBALS
 $GLOBALS is a PHP super global variable which is
used to access global variables from anywhere in the
PHP script (also from within functions or methods).
 PHP stores all global variables in an array called
$GLOBALS[index]. The index holds the name of the
variable.
<?php
$m1 = 75;
$m2 = 25;

function add() {
$GLOBALS['s'] = $GLOBALS['m1'] +
$GLOBALS['m2'];
}

add();
echo $s, $GLOBALS['s'];
?>
output 100 100
<?php
$name= ‘Ahmad’;
Function display()
{
Global $name;
Return ‘my name is ‘.$name;
}
Echo display();
?>
 We will write the previous example in other way using
$GLOBALS
<?php
Function display()
{
Return ‘my name is ‘.$GLOBALS [name];
}
$name = ‘Ahmad’;

Echo display();
?>
$_POST
 PHP $_POST is widely used to collect form data after
submitting an HTML form with method="post".
$_POST is also widely used to pass variables.
 The browser client can sends information to the web
server through POST.
OUTPUT
<?php
Name ali echo '
<form action="welcome.php" method="post">
Password **** Name : <input type="text" name="name"><br>
Password: <input type=“password"
name="password"><br>
submit <input type="submit">

</form> '
?> ;

<?php
echo "wellcome ",$_POST['name'],"<br />";
welcome ali
echo " your password is :",$_POST['password'],"<br />";
your password is :ali2 ?>
PHP $_GET
 PHP $_GET can also be used to collect form data after
submitting an HTML form with method="get".
 $_GET can also collect data sent in the URL.
OUTPUT

Words

Search
Search

http://localhost/test/get1.php?getdata=ali
NOTES
 $_GET is an array of variables passed to the current
script via the URL parameters.

 $_POST is an array of variables passed to the current


script via the HTTP POST method.
WHEN TO USE GET?
 The GET method is visible to everyone (all variable
names and values are displayed in the URL).
 GET also has limits on the amount of information to
send. The limitation is about 2000 characters.
 Because the variables are displayed in the URL, it is
possible to bookmark the page.
 GET should NEVER be used for sending passwords or
other sensitive information
WHEN TO USE POST?
 Information sent from a form with the POST method is
invisible to others (all names/values are embedded
within the body of the HTTP request).
 POST has no limits on the amount of information to
send.
 Because the variables are not displayed in the URL, it
is not possible to bookmark the page
PHP $_REQUEST
 PHP $_REQUEST is used to collect data after
submitting an HTML form.
 $REQUEST can get any form field value, whatever it
was GET or POST method.
<?php
<?php
echo ' if ($_REQUEST['user'] ==
<form action="request.php" method="post"> 'Ahmad')
Name : <input type="text" name="user"><br> { echo 'Ahmad likes PHP';
}
<input type="submit">
else if($_REQUEST['user'] ==
</form> ' ; 'Muna')
{ echo 'Muna loves php'; }
?> else
echo ' user is not defined';
?>

Name: sami user is not defined


Submit

You might also like