Java Techies- Solution for All
Array
- Arrays store element values in association with key values rather than index order.
- Array is a collection of variables indexed and bindss together into a single, easily referenced super-variable.
- An array offers simple way to pass multiple values between lines of code, functions, and even pages.
- Arrays consist container for doing manipulations (sorting, counting, and so on) of any data you develop while executing a single page's script.
Example :
<?php $Mobile=array("LAVA","MICROMAX","SAMSUNG","LG"); echo "I like " . $Mobile{0}. ", " . $Mobile{1} . " and " . $Mobile{2}. "."; ?>
Output :
I like LAVA, MICROMAX and SAMSUNG.
Creating an Arrays
-
Three main ways to create an array in a PHP script that happens to
return an array as its value :
- By assigning a value into one.
- By using the array() construct.
- By calling a function.
Direct assignment
- To create an array is to act as though a variable is already an array and assign a value into it.
Example :
$my_arr[1] = "Direct Assignment";
The array() construct :
- To create an array is through the array() construct, which use to creates a new array from the specification of its elements and associated keys.
- array() is called with no arguments, which creates a new empty array.
- Next simplest version, array() takes a comma-separated list of elements to be stored, without any specification of keys.
- The array will remember the order in which the elements were stored.
- The assignment to $fruit_basket, then, has exactly the same effect as the following:
$Mobile[0] = 'LAVA'; $Mobile[1] = 'SAMSUNG'; $Mobile[2] = 'LG'; $Mobile[3] = 'NOKIA';
Example :
$Mobile= array('LAVA', 'SAMSUNG', 'LG', 'NOKIA');
By calling a function.
- To create an array in a script is to call a function that returns an array.
- It may be a user-defined function, or built-in function that makes an array via methods internal to PHP.
- Some or Many database-interaction functions, for example, return their results in arrays that the functions create on the fly.
- One such is
range()
,between the arguments, which takes two integers as arguments and returns an array filled with all the integers .
$my_array = range(4,8); Or Equals to $my_array = array(4, 5, 6, 7, 7);
Some Sort Functions For Arrays
Methods | Description |
---|---|
sort() |
This Function sort arrays in ascending order. |
rsort() |
This Function sort arrays in descending order. |
asort() |
This Function sort associative arrays in ascending order, according to the value. |
ksort() |
This Function sort associative arrays in ascending order, according to the key. |
arsort() |
This Function sort associative arrays in descending order, according to the value. |
krsort() |
This Function sort associative arrays in descending order, according to the key. |
Example :
<?php $numbers=array(2,34,35,89,90); rsort($numbers); $arrlength=count($numbers); for($x=0;$x<$arrlength;$x++) { echo $numbers[$x]; echo "
"; } ?>
Output :
90 89 35 34 2