Tuesday, June 26, 2012

PHP Learning - View and Modify Arrays

In my last lesson, I talked about how to create arrays, and we are going to continue today by starting with the topic of how to view arrays in php, then we will look into how to modify arrays in php.
You can see the structure and values of any array by using one of two
statements — var_dump or print_r. The print_r() statement, however,
gives somewhat less information. To display the $studying_day array, use
the following statement:
print_r($studying_day); and you will get the output:
Array
(
[1] => english
[2] => french
[3] => math
[4] => business
)
To get a more detailed information other than the key and value, you can use:
var_dump($studying_day);

array(3) {
[1]=>
string(7) “english”
[2]=>
string(6) “french”
[3]=>
string(4) “math”
[4]=>
string(8)"business"
}
Arrays can be changed at any time in the script, just as variables can.
Let's say I am sick of english(actually I am), thus i decided not to study english anymore, then I can use the following statement to remove it from my previously made array:
$studying_day[1] = " "; # this set the value to empty, but it does not remove
unset(studying_day[1]); # this statement completely remove it from the group
Sort Array:
One of the most useful features of arrays is that PHP can sort them for you.
To sort my array, I can use the statement: sort($studying_day);
$studying_day[1]="english";
$studying_day[2]="french";
$study_day[3]="math";
$study_day[4]="business";
To sort array that contains word as key, we use asort($arrayname); for example, we have a new array:
$computer[cpu]="AMD";
$computer[mainboard]="ESC";
$computer[keyboard]="BENQ";
$computer[screen]="LCD";
when I use asort($computer), I get the following results:
$computer[cpu]="AMD";
$computer[keyboard]="BENQ";
$computer[mainboard]="ESC";
$computer[screen]="LCD";
Some other useful sorting include:
rsort($arrayname) #Sorts by value in reverse order; assigns new numbersas the keys.
ksort($arrayname) #Sorts by key.
krsort($arrayname) #Sorts by key in reverse order.
usort($arrayname, function) #Sorts by a function.


View the original article here

No comments:

Post a Comment