Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu PHP and MySQL by Example- P6 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.49 MB, 50 trang )

A parse error occurred because single quotes were embedded within double quotes. This can be fixed by concatenating
the strings as follows:
echo $book['Title'] . "<br />";
!
or by surrounding the array element with curly braces:
echo "{$book['Title']}<br />"
!
Do not eliminate the quotes around the key as shown here:
echo $book[Title];
!
as PHP will treat the key Title as a constant, not as a string. You might inadvertently use a key value that has been
defined somewhere else as a constant to produce the error message “E_NOTICE (undefined constant).”
Mixing Elements in an Array
The index/key value in an array can be a positive or negative number or a string, and the value associated with it can be
a string, a number, another array, and so on. If an index value is not given, PHP provides a numeric index, incrementing
the index of the next position in the array by 1.
Example 8.7 demonstrates how the index and the value of the elements can be mixed. The output is shown in Figure
8.11.
Example 8.7.
<html>
<head><title>Using a Negative Index</title></head>
<body bgcolor="lightgreen">
<b>
<?php
1 $colors=array(-1 =>'purple','orange',"brown"=>"burnt
sienna");
2 $colors[]=255;
3 echo "\$colors[-1] is ". $colors[-1] . ".<br />";
4 echo "\$colors[0] is $colors[0].<br />";
echo "\$colors[1] is $colors[1].<br />";
5 echo "\$colors['brown'] is " . $colors['brown'] . ".<br


/>";
6 // echo "\$color['brown'] is {$colors['brown']}<br />";
?>
</b>
</body>
</html>
Explanation
"
#$%!,)),-!$colors!03,)30!2*3$!,!&%4,3*6%!*&/%:7!-18!?@?!2* !,//!"!35!%,+$!
+5&0%+'3*6%!*&/%:!*&!3$%!,)),-7!05!3$,3!%.%(%&3!'orange'!2* !;%!,005+*,3%/!
2*3$!*&/%:!<8!#$%!3$*)/!%.%(%&3!*0!,!03)*&47!"brown"7!,005+*,3%/!2*3$!"burnt
sienna"8!K1!,&53$%)!%.%(%&3!*0!,//%/!.,3%)!5&7!3$%!*&/%:!2* !;%!&'(%)*+!,&/!
*&+)%(%&3%/!;-!"!1)5(!3$%!.,03!&'(%)*+!*&/%:8
9
>!&%2!%.%(%&3!*0!,//%/!35!3$%!,)),-8!T%+,'0%!3$%!.,03!&'(%)*+!*&/%:!2,0!<7!3$%!
*&/%:!51!3$*0!%.%(%&3!2* !;%!"8
=
#$%!6,.'%!51!3$%!,)),-!%.%(%&3!,3!*&/%:!Q"!*0!%:3),+3%/!,&/!B)*&3%/8
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
A
>.3$5'4$!3$%!6,.'%!'orange'!2,0!&53!%:B.*+*3 !,00*4&%/!,&!*&/%:7!?@?!2* !
,//!"!35!3$%!B)%6*5'0!&'(%)*+!*&/%:!6,.'%8!T%+,'0%!3$,3!*&/%:!2,0!Q"7!3$%!
*&/%:!15)!'orange'!2* !;%!,00*4&%/!<8
R
@%)%!3$%!*&/%:!*0!,!03)*&47!"brown"7!,005+*,3%/!2*3$!,!6,.'%7!"burnt sienna"8!
L0*&4!,!03)*&4!2* !$,6%!&5!%11%+3!5&!3$%!&'(%)*+!*&/%:%08
V
#$*0!.*&%!*0!+5((%&3%/!5'37!;'3!B)56*/%/!35!/%(5&03),3%!3$%!'0%!51!+') !
;),+%0!2$%&!'0*&4!,)),-0!,&/!&%03%/!W'53%0U!3$,3!*07!W'53%0!2*3$*&!W'53%08!
Y$%&!,&!,)),-!%.%(%&3!*0!%&+.50%/!2*3$*&!,!03)*&4!*&!/5';.%!W'53%07!3$%!+') !

;),+%0!, 52!3$%!J%-!35!;%!0'))5'&/%/!;-!0*&4.%!W'53%07!2*3$5'3!+,'0*&4!,!?@?!
%))5)8!Y*3$5'3!3$%!+') !;),+%0!3$%!%))5)!*0I!?,)0%!%))5)I!0-&3,:!%))5)7!
'&%:B%+3%/!#ZOXG>?PO[Z>X[ZY@K#OP?>GO7!%:B%+3*&4!#ZP#\X]!5)!
#H>\K>TNO!5)#ZXLMZP#\KX]!*&GI^^2,(B^B$B_!5&!.*&%!"E

Figure 8.11. Mixed array elements. Output from Example 8.7.

!
8.1.3. Printing an Array
There are a number of ways to print the contents of an array. PHP provides built-in functions to display all of the keys
and values, or you can use loops. We discuss the built-in functions first.
The print_r() Function
The print_r() built-in function displays detailed information about a variable, such as its type, length, and contents.
It displays the value of a string, integer, or float. In the case of arrays, print_r() displays all of the elements of an
array; that is, the key–value pairs. (Use the HTML <pre> tag, to display each element on a separate line; otherwise,
the output is displayed on one line.) If you would like to capture the output of print_r() in a variable, set the return
parameter to boolean TRUE. The print_r() function can also be useful when debugging a program.
Remember that print_r() will move the internal array pointer to the end of the array. Use reset() to bring it back
to the beginning. PHP 5 appears to reset the pointer automatically after using print_r().
Example 8.8 demonstrates the print_r() function. The output is shown in Figure 8.12.



Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Format
bool print_r ( mixed expression [, bool return] )
!
Example:
print_r($colors); // Display the contents of the array $list=print_r( $colors,
true); // Save the return value in $list reset($colors); // Move internal array

pointer to array beginning

Example 8.8.
<html>
<head><title>The print_r() Function</title></head>
<body bgcolor="yellow">
<b>
<pre>
<?php
1 $colors=array('red','green', 'blue','yellow');
2 $book=array('Title' => 'War and Peace',

'Author' => 'Tolstoy',

'Publisher' => "Oxford University Press",
);
3 print_r($colors);
echo "<hr>";
4 print_r($book);
?>
</b>
</pre>
</body>
</html>




Explanation
"

>!&'(%)*+!,)),-!+, %/!$colors!*0!+)%,3%/!2*3$!15')!%.%(%&308
9
>&!,005+*,3*6%!,)),-!+, %/!$book!*0!+)%,3%/!2*3$!J%-Q6,.'%!B,*)08
=
#$%!print_r()!1'&+3*5&!/*0B.,-0!3$%!,)),-!*&!,!$'(,& !)%,/,;.%!15)(,37!
&'(%)*+!*&/%:%0!5&!3$%!.%13!51!3$%!=>!5B%),35)!,&/!3$%!6,.'%!51!3$%!%.%(%&30!5&!
3$%!)*4$3!0*/%8!L0%!3$%!@#MN!<pre>!3,4!35!B)%0%&3!3$%!,)),-!5&!0%B,),3%!.*&%0U!
53$%)2*0%!*3!2* !;%!/*0B.,-%/!,0!5&%!.5&4!.*&%8
A
#$%!print_r()!1'&+3*5&!/*0B.,-0!3$%!,005+*,3*6%!,)),-7!J%-Q6,.'%!B,*)0!*&!,&!
%,0-_35_)%,/!15)(,38


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 8.12. Printing an array with the print_r() function. Output from Example 8.8.
!
!
!
Example 8.9.
<html>
<head><title>The print_r() Function</title></head>
<body bgcolor="CCFF66">
<pre>
<b>
<?php
$colors=array('red','green', 'blue','yellow');
$book=array('Title' => 'War and Peace',
'Author' => 'Tolstoy',
'Publisher' => 'Oxford University Press',
);

1 $display= print_r($colors,true);// Assign output to
$display
2 echo $display;
3 reset($colors);
?>
</b>
</pre>
</body>
</html>

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Explanation
"
T-!4*6*&4!print_r()!,&!,//*3*5&,.!;55.%,&!,)4'(%&3!51!TRUE7!-5'!+,&!+,B3')%!3$%!
5'3B'3!51!print_r()!*&!,!6,)*,;.%8
9
#$%!$display!6,)*,;.%!+5&3,*&0!3$%!5'3B'3!51!3$%!print_r()!1'&+3*5&U!3$,3!*07!3$%!
+5&3%&30!51!3$%!,)),-8!P%%!D*4')%!E8"=8
=
#$%!reset()!1'&+3*5&!B'30!3$%!*&3%)&,.!,)),-!B5*&3%)!;,+J!,3!3$%!;%4*&&*&4!51!3$%!,)),-8!
#$%!?@?!(,&',.!0'44%030!'0*&4!3$*0!1'&+3*5&!35!)%0%3!3$%!,)),-!B5*&3%)7!;'3!*&!?@?!R!*3!*0!
&53!&%+%00,)-8
!
Figure 8.13. Saving the output from print_r() in a variable. Output from Example 8.9.


The var_dump() Function
The var_dump() function displays the array (or object), the number of elements, and the lengths of each of the string
values. It also provides output with indentation to show the structure of the array or object. (See Chapter 17, “Objects,”

for more on objects.)
Example 8.10 demonstrates the var_dump() function. The output is shown in Figure 8.14.
Format
void var_dump ( mixed expression [, mixed expression [, ]] )
!
Example:
$states=array('CA' => 'California','MT'=>'Montana','NY'=>'New York');
var_dump($states); // Dumps output in a structured format

Example 8.10.
<html>
<head><title>The var_dump() Function</title></head>
<body bgcolor="CCFF99">
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
<pre>
<b>
<?php
1 $colors=array('red','green', 'blue','yellow');
2 $book=array('Title' => 'War and Peace',
'Author' => 'Tolstoy',
'Publisher' => "Oxford University Press",
);
3 var_dump($colors);

var_dump($book);
?>
</b>
</pre>
</body>
</html>

Explanation
"
#$%!&'(%)*+!,)),-7!$colors7!*0!,00*4&%/!,!.*03!51!+5.5)08
9
#$%!,005+*,3*6%!,)),-7!$book7!*0!,00*4&%/!J%-Q6,.'%!B,*)08
=
#$%!var_dump()!1'&+3*5&!3,J%0!3$%!&,(%!51!3$%!,)),-!,0!*30!,)4'(%&37!,&/!
/*0B.,-0!3$%!5'3B'3!;-!1*)03!B)*&3*&4!3$%!&'(;%)!51!%.%(%&30!*&!3$%!,)),-7!*&/%:!
6,.'%7!,&/!3$%&!3$%!&'(;%)!51!+$,),+3%)0!*&!%,+$!51!3$%!,00*4&%/!03)*&4!6,.'%0!
,&/!*30!6,.'%8!P%%!D*4')%!E8"A8


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 8.14. Printing an array with the var_dump() function. Output Example 8.10.

!
8.1.4. Using Loops to Access Array Elements
Loops make it easy to step through an array. The for and while loops are useful for numeric arrays where you can
determine the size, and starting point of the array is usually 0, incremented by 1 for each element. The best way to loop
through an associative array is with the foreach loop, although you can use this loop for numerically indexed arrays
as well.

The for Loop
The for loop can be used to iterate through a numeric array. The initial value of the for loop will be the first index
value of the array, which will be incremented each time through the loop until the end of the array is reached.
Example 8.11 demonstrates how the for loop is used to view each element of an array. The output is displayed in
Figure 8.15.
Example 8.11.
<html>
<head><title>The for Loop</title></head>

<body bgcolor="lightgreen">
<table border="1" bordercolor="black" bgcolor="yellow">
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
<caption>Elements</caption>
<?php
1 $colors=array('red','green', 'blue','yellow');
2 for($i = 0; $i < count($colors); $i++){
3 echo "<tr><td><b>$colors[$i]</b></td></tr>";
}
?>
</table>
</body>
</html>
Explanation
"
#$%!&'(%)*+!,)),-7!$colors7!*0!,00*4&%/!,!.*03!51!+5.5)08
9
#$%!1*)03!,)4'(%&3!35!3$%!for!.55B7!$i = 07!0%30!3$%!*&*3*,.!6,.'%!51!$i!35!07!
2$*+$!)%B)%0%&30!3$%!1*)03!*&/%:!*&!3$%!,)),-8!K1!3$%!*&/%:!6,.'%7!$i7!*0!.%00!3$,&!
3$%!0*`%!51!3$%!,)),-!C)%3')&%/!1)5(!3$%!count()!1'&+3*5&F7!3$%!.55B!;5/-!*0!
%&3%)%/7!,13%)!/*0B.,-*&4!3$%!+5.5)7!3$%!3$*)/!,)4'(%&3!51!3$%!for!.55B!*0!
%:%+'3%/U!3$,3!*07!*&+)%(%&3!3$%!6,.'%!51!$i!;-!"8
=
O,+$!3*(%!3$)5'4$!3$%!.55B7!3$%!&%:3!%.%(%&3!*&!3$%!$colors!,)),-!*0!/*0B.,-%/!
*&!,!3,;.%!+% 8


Figure 8.15. Using the for loop to loop through an array. Output from Example 8.11.
!
!

The while Loop
The while loop can be used to iterate through a numeric array as shown in Examples 8.12 and 8.13.
By setting the initial value to 0, the loop will iterate from the first element of the array (assuming that the array starts at
element zero) until it reaches the end of the array. The count() or sizeof() functions can be used to find the
length of the array.

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 8.12.
<html>
<head><title>The while Loop</title></head>
<body bgcolor="lightgreen">
<table border='1' bordercolor='black' bgcolor='yellow'>
<caption>Elements</caption>
<?php
1 $colors=array('red','white', 'aqua','yellow');
2 $i = 0;
3 while( $i < count($colors)){
4 echo "<tr bgcolor=$colors[$i]><td><b>$colors[$i]
</b></td></tr>";
5 $i++;
}
?>
</table>
</body>
</html>
Explanation
"
>!&'(%)*+!,)),-!+, %/!$colors!*0!+)%,3%/!,&/!,00*4&%/!03)*&4!6,.'%08
9
H,)*,;.%7!$i7!0%3!35!<7!2* !;%!3$%!*&*3*,.!6,.'%!*&!3$%!.55B7!,&/!2* !'0%/!,0!3$%!,)),-a0!

*&/%:8
=
#$%!count()!1'&+3*5&!)%3')&0!3$%!&'(;%)!51!%.%(%&30!*&!3$%!,)),-8!#$%!while!
%:B)%00*5&!3%030!3$,3!3$%!6,.'%!51!$i!*0!.%00!3$,&!3$%!0*`%!51!3$%!,)),-8
A
#$%!6,.'%!51!$i!2* !;%!'0%/!,0!3$%!*&/%:!6,.'%!51!3$%!,)),-7!$colors8!O,+$!3*(%!3$)5'4$!
3$%!.55B7!3$%!6,.'%!2* !;%!*&+)%(%&3%/!;-!"8!K&!3$*0!%:,(B.%7!3$%!6,.'%!51!3$%!%.%(%&37!
,!+5.5)7!2* !;%!'0%/!,0!3$%!;,+J4)5'&/!+5.5)!15)!3$%!+'))%&3!)527!,&/!,0!3$%!3%:3!
B)*&3%/!2*3$*&!3$%!3,;.%a0!/,3,!+% 8!P%%!D*4')%!E8"V8
R
#$%!6,.'%!51!$i!*0!*&+)%(%&3%/!;-!"8!K1!-5'!15)4%3!35!*&+)%(%&3!$i7!3$%!.55B!2* !45!
15)%6%)!;%+,'0%!$i!2* !,.2,-0!;%!.%00!3$,&!3$%!0*`%!51!3$%!,)),-8
!














Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 8.16. Using the while loop to iterate through an array. Output from Example 8.12.




Example 8.13.
G5/%!H*%2I!
<html><head><title>Table Colors</table></head>
<body bgcolor="blue">
<table border=1 bordercolor="white" align="center"
cellpadding="2">
<caption><b><font size="+2" color="yellow">Colored
Rows</font></b>
</caption>
<?php
1 $colors=array("orange","lightgreen", "lightblue","yellow");
2 $i=0;
3 while ( $i< 8 ){
// Each time through the loop the index value in the
array
// will be changed, with values 0, 1, 2, 3, 0, 1, 2, 3,
etc.
4 $color=$colors[$i%4];
?>
<tr bgcolor="<?=$color?>">
5 <td><?=$color?></td>
<td><?=$color?></td>
<td><?=$color?></td>
<td><?=$color?></td>
<td><?=$color?></td>
</tr>
<?php
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

6 $i++; // Increment the value of the loop counter
7 }
?>
</body>
</html>
Explanation
"
>&!,)),-!+, %/!$colors!*0!,00*4&%/!15')!+5.5)!6,.'%08
9
#$%!6,)*,;.%7!$i7!*0!*&*3*,.*`%/!35!<8
=
#$%!while!.55B!%6,.',3%0!3$%!%:B)%00*5&!*&!B,)%&3$%0%08!K0!3$%!6,.'%!51!$i!.%00!
3$,&!Eb!K1!*3!*07!3$%!.55B!;5/-!*0!%&3%)%/8
A
#$%!*&/%:!6,.'%!51!3$%!$colors!,)),-!*0!/*6*/%/!;-!A!,&/!3$%!)%(,*&/%)!
C(5/'.'0F!*0!)%B.,+%/!,0!3$%!&%2!*&/%:!6,.'%8
R
#$%!1*)03!3*(%!*&!3$%!.55B!3$%!*&/%:!*0!<8!#$%!6,.'%!$color[0]!*0!"orange"!,&/!
2* !;%!1* %/!*&!3$%!3,;.%!15)!,!)52!51!R!3,;.%!+% 08!P%%!D*4')%!E8"S8
V
#$%!6,.'%!51!$i!*0!*&+)%(%&3%/!;-!"8!X%:3!3*(%!3$)5'4$!3$%!.55B7!$color[1]!*0!
"lightgreen"!,&/!3$,3!+5.5)!2* !1* !,!)52!51!3,;.%!+% 08
S
#$*0!*0!3$%!+.50*&4!;),+%!15)!3$%!while!.55B8
Figure 8.17. The while loop and arrays. Output from Example 8.13.
!

The foreach Loop
The foreach statement is designed to work with both numeric and associative arrays (works only on arrays). The
loop expression consists of the array name, followed by the as keyword, and a user-defined variable that will hold each

successive value of the array as the loop iterates. The expression in the foreach statement can include both the key
and value as shown in Example 8.14. The foreach loop operates on a copy of the original array. If you change the
value of an element of the array, it will only change the copy, not the value in the original.


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Format
(Numeric Array)
foreach ($array_name as $value){
do-something with the element's value;
}
foreach($array_name as $index=>$value){
do-something with the element's index and value
}

Example:
$suit=("diamond", "spade", "club", "heart");
foreach ( $suit as $card_type){
echo $card_type . "<br />"; // displays: diamond
}
spade

club

heart
(Associative Array)
foreach ($array_name as $key => $variable){
do-something $key and/or $variable;
}


Example:
$courses=("101A"=>"Intro to CS",
"200B"=>"Data Structures",
"130A"=>"Visual Basic"
);
foreach ( $courses as $number=>$class_name){
echo $number . '=>' . $class_name . "<br />"; // displays keys

// and values
}
Example 8.14.
G5/%!H*%2I!!
<html>
<head><title>The foreach Loop</title></head>
<body bgcolor="lightgreen">
<b>
<?php
1 $colors=array('red','green', 'blue', 'yellow');
2 $employee=array('Name' => 'Jon Doe',
'ID' => '23d4',
'Job Title'=> 'Designer',
'Department'=>'Web Development',
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
);
3 foreach ($colors as $value){// Each value is stored in
$value

echo "$value <br />";
}
echo "<hr>";

4 foreach ($employee as $key => $value){// Associative array

echo "employee[$key] => $value<br />";
}
?>
</b>
</body>
</html>
Explanation
"
>!&'(%)*+!,)),-!51!15')!+5.5)0!*0!/%1*&%/8
9
>&!,005+*,3*6%!,)),-!51!15')!J%-Q6,.'%!B,*)0!*0!/%1*&%/8
=
#$%!foreach!.55B!*0!'0%/!35!*3%),3%!3$)5'4$!%,+$!%.%(%&3!51!3$%!$colors!,)),-8!
#$%!%:B)%00*5&!$colors as $value7!(%,&0I!K&!3$%!$colors!,)),-!,00*4&!3$%!
6,.'%!51!%,+$!%.%(%&3!35!3$%!6,)*,;.%!$value7!5&%!,3!,!3*(%7!'&3*.!3$%!,)),-!
%&/08!O,+$!6,.'%!2* !;%!/*0B.,-%/!*&!3')&8!P%%!D*4')%!E8"E8
A
#$*0!foreach!.55B!*3%),3%0!3$)5'4$!%,+$!J%-Q6,.'%!B,*)!51!,&!,005+*,3*6%!,)),-7!
+, %/!employee8!#$%!,)),-!&,(%!*0!15 52%/!;-!3$%!as!J%-25)/!,&/!,!6,)*,;.%!
35!)%B)%0%&3!3$%!J%-7!+, %/!$key7!15 52%/!;-!3$%!=>!5B%),35)7!,&/!,!6,)*,;.%!35!
)%B)%0%&3!3$%!6,.'%7!+, %/!$value8
Figure 8.18. Looping through an array with the foreach loop. Output from Example 8.14.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Modifying a Value by Reference with a foreach Loop
As of PHP 5, you can easily modify an array’s elements by preceding the value after the as keyword with &. This will
assign by reference instead of copying the value; that is, whatever you do to the array while in the loop will change the

original array, not a copy of it.
Example 8.15.
G5/%!H*%2I!
<html>
<head><title>The foreach Loop Changing Values by Reference
</title></head>
<body bgcolor="lightblue">
<b>
<pre>
Original array
<?php
1 $val="hello";
2 $years=array(44, 53, 64, 77);
3 print_r($years);
4 foreach ($years as &$val){// $val is a reference
5 $val += 1900;
echo "$val<br />"; // $val is global in scope
}
6 echo "After foreach: \$val=$val<br />";
?>
<hr>
Array has been changed
<?php
7 print_r($years);
?>
</pre>
</b>
</body>
</html>
Explanation

"
>!6,)*,;.%7!$val7!*0!,00*4&%/!3$%!03)*&47"hello"8
9
>!&'(%)*+!,)),-7!+, %/!$years7!*0!,00*4&%/!15')!&'(;%)08
=
#$%!print_r()!1'&+3*5&!B)*&30!3$%!5)*4*&,.!,)),-8!P%%!D*4')%!E8"c8
A
K&!3$%!foreach!%:B)%00*5&!3$%!6,)*,;.%!$val!*0!'0%/!,0!,!)%1%)%&+%!35!%,+$!%.%(%&3!51!3$%!
$years!,)),-8!#$%!&!B)%+%/*&4!3$%!6,)*,;.%!&,(%!(,J%0!*3!,!)%1%)%&+%8!>&-!+$,&4%0!
(,/%!35!3$%!6,.'%!3$,3!$val!)%1%)%&+%0!2* !+$,&4%!3$%!5)*4*&,.!,)),-8
R
1900!*0!,//%/!35!%,+$!6,.'%!*&!3$%!,)),-!6*,!3$%!)%1%)%&+%7!$val8
V
T%+,'0%!$val!*0!,!4.5;,.!6,)*,;.%!C*8%87!6*0*;.%!3$)5'4$5'3!3$%!B)54),(F7!*30!5)*4*&,.!6,.'%!
*0!+$,&4%/!*&!3$%!foreach!.55B7!,&/!3$%!.,03!6,.'%!,00*4&%/!35!*3!)%(,*&0!,13%)!3$%!.55B!
%:*308
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
*0!+$,&4%/!*&!3$%!foreach!.55B7!,&/!3$%!.,03!6,.'%!,00*4&%/!35!*3!)%(,*&0!,13%)!3$%!.55B!
%:*308
S
#$%!print_r()!1'&+3*5&!B)*&30!3$%!(5/*1*%/!,)),-8!P%%!D*4')%!E8"c8
!
Figure 8.19. Modifying values by reference. Output from Example 8.15.


8.1.5. Checking If an Array Exists
PHP makes it possible to check to see if an array exists, and to check for the existence of keys, values, or both. See
Table 8.2.
Table 8.2. Functions to Check for Existence of an Array
Function

What+It+Does
array_key_exists()
G$%+J0!*1!3$%!4*6%&!J%-!5)!*&/%:!%:*030!*&!3$%! ,)),-
in_array()
G$%+J0!*1!,!6,.'%!%:*030!*&!,&!,)),-
is_array()
G$%+J0!*1!3$%!6,)*,;.%!*0!,&!,)),-U!)%3')&0!TRUE!5)!FALSE
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 8.16 demonstrates how to perform array checks using the functions in Table 8.2. The output is displayed in
Figure 8.20.
Example 8.16.
G5/%!H*%2I!
<html>
<head><title>Checking for Existence of an Array or Element
</title></head>
<body bgcolor="lightblue">
<h3>Does it Exist?</h3>
<pre>
<?php
1 $country="USA"; // $country is a scalar
2 $states=array('CA'=>"California",
'MT'=>"Montana",
'VA'=>"Virginia");
3 if ( is_array($country)){
print '$country is an array'."<br />";
}
else{
print '$country is not an array'."<br />";
}

4 if (array_key_exists("VA", $states)){
print 'Array key "VA" exists'."<br />";
}
5 if (in_array("Montana", $states)){
print 'Array value "Montana" exists'."<br />";
}
?>
<pre>
</body>
</html>
Explanation
"
>!0*(B.%!0+,.,)!6,)*,;.%!+, %/!$country!*0!,00*4&%/!3$%!03)*&4!"USA"8
9
>&!,005+*,3*6%!,)),-!+, %/!$states!*0!,00*4&%/!J%-Q6,.'%!B,*)08
=
#$%!is_array()!;'*.3_*&!1'&+3*5&!)%3')&0!3)'%!*1!*30!,)4'(%&3!*0!,&!,)),-7!,&/!
1,.0%!*1!*3!*0!&538!$states!*0!&53!,&!,)),-8
A
#$%!array_key_exists()!;'*.3_*&!1'&+3*5&!)%3')&0!3)'%!*1!*30!,)4'(%&3!*0!3$%!
J%-!5)!*&/%:!*&!,&!,)),-8
R
#$%!in_array()!;'*.3_*&!1'&+3*5&!)%3')&0!3)'%!*1!*30!,)4'(%&3!*0!,!6,.'%!3$,3!
%:*030!*&!,&!,)),-8!#$%!,)),-!6,.'%!"Montana"!/5%0!%:*03!*&!3$%!$states!
,005+*,3*6%!,)),-8




Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Figure 8.20. Checking an array’s existence.
!
!
8.1.6. Creating Strings from Arrays and Arrays from Strings
In Chapter 6, “Strings,” we discussed strings and their many functions. Now that we have learned about arrays, PHP
provides functions that serve the dual purpose of creating arrays from strings and strings from arrays (see Table 8.3).
Table 8.3. Arrays and Strings
Function
What+It+Does
explode()
PB.*30!'B!,!03)*&4!;-!,!0B%+*1*%/!/%.*(*3%)!,&/!+)%,3%0!,&!,)),-!51!03)*&40
implode()
G)%,3%0!,!03)*&4!;-!4.'*&4!354%3$%)!,)),-!%.%(%&30!;-!,!0B%+*1*+!0%B,),35)
join()
>.*,0!15)!implode()
split()
PB.*30!'B!,!03)*&4!*&35!,&!,)),-!;-!,!)%4'.,)!%:B)%00*5&!C0%%!G$,B3%)!"97!d\%4'.,)!
O:B)%00*5&0!,&/!?,33%)&!M,3+$*&4eF
!
The implode() Function
The implode() function creates a string by joining together the elements of an array with a string delimiter, called
the glue string. As of PHP 4.3.0, the glue parameter of implode() is optional and defaults to the empty string("").
Another name for implode() is its alias, join().
The implode() function returns a string containing a string representation of all the array elements in the same order,
with the glue string between each element.
Format
string implode ( string glue, array elements )
!
Example:
$stats_array = array('name', 'ssn', 'phone'); // implode() creates a string from

an array $stats_string = implode(",", $array);

The explode() Function
The explode() function splits up a string and creates an array, the opposite of implode(). The new array is
created by splitting up the original string into substrings based on the delimiter given. The delimiter is what you
determine is the word separator, such as a space or comma. If given a limit, the new array will be limited to that many
substrings, and the last one will contain the rest of the string. See also “The preg_split() Function—Splitting Up
Strings” on page 510.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 8.17 demonstrates how the explode function works. Its output is displayed in Figure 8.21.
Format
array explode(string separator, string string [, int limit])
!
Example:
$fruit = explode(" ", "apples pears peaches plums") //Creates a 4-element array
$fruit = explode("|", "apples|pears|peaches|plums",3) echo $fruit[0],
$fruit[1], $fruit[2]; // Creates a 3-element array
Example 8.17.
<head><title>explode() Array</title></head>
<body bgcolor="black">
<font size="+1" color="white">
<pre>
<?php
1 $colors="red green orange blue";// Create a string
2 echo "<b>\$colors is a ". gettype($colors)."\n";
3 $colors=explode(" ",$colors);// Split up the string by
spaces
echo "<img src='explosion.jpg'>","\n";
4 echo "<b>After explode():\$colors is an ".
gettype($colors)."\n";

print_r($colors);
// Let's give explode() second parameter limiting
// array size to 3 elements
5 $colors=explode(" ","red green orange blue",3);
echo "\n";
6 print_r($colors);
?>
</pre>
</body>
</html>
Explanation
"
>!6,)*,;.%!+, %/!$colors!*0!+)%,3%/!,&/!,00*4&%/!,!03)*&48
9
#$%!gettype()!1'&+3*5&!)%3')&0!3$%!/,3,!3-B%!51!3$%!6,)*,;.%7!,!03)*&48
=
#$%!explode()!1'&+3*5&!0B.*30!'B!3$%!03)*&4!2*3$!2$*3%0B,+%!,0!3$%!0%B,),35)!
,&/!+)%,3%0!,&!,)),-!+, %/!$colors8
A
>13%)!explode()7!3$%!3$%!gettype()!1'&+3*5&!)%3')&0!3$%!/,3,!3-B%!51!$colors7!
,&!,)),-8
R
#$*0!3*(%!3$%!explode()!1'&+3*5&!*0!4*6%&!,&!5B3*5&,.!0%+5&/!B,),(%3%)7!
2$*+$!2* !.*(*3!3$%!&%2!,)),-!+)%,3%/!35!,!.%&43$!51!3$)%%!%.%(%&308
V
#$%!&%2!,)),-!+5&0*030!51!3$)%%!%.%(%&307!3$%!.,03!%.%(%&3!+5&3,*&0!;53$!
"orange blue"7!3$%!)%(,*&/%)!51!3$%!03)*&4!,13%)!*3!2,0!/*6*/%/!*&35!3$)%%!
,)),-!%.%(%&308

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Figure 8.21. Converting a string to an array with the explode() function. Output from Example 8.17.

8.1.7. Finding the Size of an Array
PHP provides built-in functions to count the number of elements in an array. They are count(), sizeof(), and
array_count_values(). Example 8.18 demonstrates how to find the size of a multidimensional array.
Table 8.4. Functions to Find the Size of an Array
Function
What+It+Does
array_count_values()
\%3')&0!,&!,)),-!+5&0*03*&4!51!3$%!6,.'%0!51!,&!,)),-!,&/!3$%!
&'(;%)!51!3*(%0!%,+$!6,.'%!5++')0!*&!,&!,)),-
count()
\%3')&0!3$%!&'(;%)!51!%.%(%&30!*&!,&!,)),-!5)!B)5B%)3*%0!51!,&!
5;f%+3
sizeof()
\%3')&0!3$%!0*`%!51!3$%!,)),-7!0,(%!,0!count()
!
The count() and sizeof() Functions
The count()
[2]
and sizeof() functions do the same thing: They both return the number of elements in an array (or
properties in an object). To find the number of elements in a multidimensional array, the count() function has an
optional mode argument that recursively counts the elements.
[2]
The sizeof() function is simply an alias for the count() function.
Format
$number_of_elments =count(array_name); $number_of_elements=count(array_name, 1);
$number_of_elements=count(array_name, COUNT_RECURSIVE)
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Example:
$bytes=range('a','z'); $size = count( $bytes); // 26 elements $size = sizeof(
$bytes); // 26 elements

Example 8.18.
<html>
<head><title>The count() function</title></head>
<body bgcolor="lightgreen">
<?php
1 $colors=array('red','green', 'blue');
2 $colors[]='yellow';
3 $size = count($colors);
4 echo "The size of the array is $size.<br />";
echo "<hr>";
?>
</body>
</html>
Explanation
"
#$%!,)),-!+, %/!$colors!*0!,00*4&%/!3$)%%!6,.'%08
9
>!&%2!%.%(%&3!*0!,//%/!35!3$%!$colors!,)),-8
=
#$%!count()!1'&+3*5&!)%3')&0!3$%!&'(;%)!51!%.%(%&30!*&!3$%!,)),-8
A
P%%!D*4')%!E899!15)!3$%!)%3')&!1)5(!3$%!count()!1'&+3*5&8

Figure 8.22. Finding the size of an array. Output from Example 8.18.

The array_count_values() Function

The array_count_values() function counts how many times a unique value is found in an array. It returns an
associative array with the keys representing the unique element of the array, and the value containing the number of
times that unique element occurred within the array.
Format
array array_count_values ( array input )
!
Example:
$hash_count = array_count_values( array("a","b", "a","a")); // Creates an
associative array with "a" and "b" as the two keys and // the number of times
each occurs in the array (the associated value)
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 8.19.
<html><head><title>Array of Colors</title></head>
<body bgcolor="lightgreen">
<pre>
<?php
1 $colors=array("red", "blue", "green", "red", "yellow",
"red","blue");
2 $unique_count = array_count_values($colors);
3 print_r($unique_count)."<br />";
?>
</pre>
</body>
</html>
Explanation
"
#$%!,))),-!+, %/!$colors!*0!+)%,3%/!2*3$!05(%!/'B.*+,3%!+5.5)08
9
#$%!;'*.3_*&!array_count_values()!1'&+3*5&!+)%,3%0!,&!,005+*,3*6%!,)),-!2*3$!3$%!J%-!
;%*&4!,!'&*W'%!6,.'%!1)5(!3$%!5)*4*&,.!,)),-!,&/!3$%!6,.'%!51!3$%!&'(;%)!51!3*(%0!3$,3!

%.%(%&3!5++')0!*&!3$%!,)),-8!K&!3$%!%:,(B.%7!3$%!+5.5)!"red"!,BB%,)0!3$)%%!3*(%07!3$%!
+5.5)!"blue"!32*+%7!,&/!3$%!+5.5)0!"green"!,&/!"yellow"!5&+%8!#$%!,005+*,3*6%!,)),-7!
$unique_count7!2* !+5&3,*&!J%-0!)%B)%0%&3*&4!3$%!+5.5)!%.%(%&3!C"red"7!"blue"7!
"green"7!"yellow"F!,&/!3$%!6,.'%!,005+*,3%/!2*3$!%,+$!+5.5)!2* !;%!3$%!&'(;%)!51!3*(%0!
3$%!+5.5)!5++'))%/!*&!3$%!,)),-8
=
#$%!print_r()!1'&+3*5&!/*0B.,-0!3$%!+5&3%&30!51!3$%!,005+*,3%/!,)),-!+)%,3%/!;-!
array_count_values()8!P%%!D*4')%!E89=8

Figure 8.23. The array_count_values() function. Outpuf from Example 8.19.
!

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
8.1.8. Extracting Keys and Values from Arrays
PHP provides functions that allow you to extract elements from an array and assign the keys and values to variables.
The array_keys() function returns all the keys in an array, the array_values() function returns all the values
of the elements in an array, and the each() function can be used to extract both keys and values.
The array_keys() Function
The array_keys() function returns all the keys of an array. If the optional search_value argument is specified,
you can get the keys for that particular value. See Example 8.20.
Format
array array_keys ( array input [, mixed search_value [, bool strict]] )
!
Example:
$array_of_keys = array_keys("apples", "pears", "peaches", "plums"); // Returns
0,1,2,3 $array_of_keys = array_keys("Title"=>"King", "Name"=>"Barbar"); //
Returns "Title", "Name"

Example 8.20.
G5/%!H*%2I!

<html><head><title>The array_keys() Function</title>
</head>
<body bgcolor="silver">
<b>
<pre>
<?php
$colors=array("red", "green", "blue", "yellow");
print"The original array:<br />";
1 $keys=array_keys($colors);
2 print_r($colors);
print"The keys:<br />";
3 print_r($keys);
echo "Key for \"blue\"<br />";
4 $keys=array_keys($colors,"blue");
print_r($keys);
?>
<hr>
<?php
5 $poem=array("Title"=>"The Raven", "Author"=>"Edgar Allen
Poe");
6 $keys=array_keys($poem);
print"The original array:<br />";
print_r($poem);
print"The keys:<br />";
print_r($keys);
?>
</pre>
</b>
</body>
</html>




Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.


Explanation
"
#$%!array_keys()!1'&+3*5&!)%3')&0!,&!,)),-!51!J%-0U!*&!3$*0!%:,(B.%!3$%!J%-0!
,)%!&'(%)*+!*&/%:!6,.'%0!03,)3*&4!,3!<8
9
#$%!print_r()!1'&+3*5&!/*0B.,-0!3$%!,)),-8!P%%!D*4')%!E89A8
=
#$%!,)),-!51!J%-0!*0!B)*&3%/8!P%%!D*4')%!E89A8
A
#$%!array_keys()!1'&+3*5&!)%3')&0!,&!,)),-!51!J%-0!5& !15)!3$%!6,.'%!"blue"!
*&!3$%!,)),-!$colorsU!3$%!J%-!5)!*&/%:!*0!98
R
>&!,005+*,3*6%!,)),-!+, %/!$poem!*0!,00*4&%/!J%-Q6,.'%!B,*)08
V
#$%!array_keys()!1'&+3*5&!)%3')&0!3$%!J%-0!*&!3$%!,005+*,3*6%!,)),-!$poemsU!
3$,3!*07!"Title"!,&/!"Author"!,)%!,00*4&%/!35!3$%!$keys!,)),-8!P%%!D*4')%!E89A8

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 8.24. Getting the keys from an array. Output from Example 8.2


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The array_values() Function
The array_values() function returns an array with all the values of the original array. The new array is indexed by

numbers. See Example 8.21 and Figure 8.25 for its output.
Format
array array_values ( array input )
!
Example:
$animals=array("tiger", "lion", "camel","elephant");
$array_of_values=array_values($animals); //
Returns:"tiger","lion","camel","elephant"

Example 8.21.
G5/%!H*%2I!
<html><head><title>The array_values() Function</title>
</head>
<body bgcolor="silver">
<b>
<pre>
<?php
1 $colors=array("red", "green", "blue", "yellow");
print"The original array:<br />";
2 $values=array_values($colors);
print_r($colors);
print"The values:<br />";
print_r($values);
?>
<hr>
<?php
3 $poem=array("Title"=>"The Raven", "Author"=>"Edgar Allen
Poe");
4 $values=array_values( $poem );
print"The original array:<br />";

print_r($poem);
print"The values:<br />";
print_r($values);
?>
</pre>
</b>
</body>
</html>











Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×