ARRAY in PHP

Arrays:
So what are Array? Well, you can think of them as several matchboxes glued together. Let us say we want to store the player names for a five-person in a soccer team in an array called $team.To do this,we could glue five matchboxes side by side and write down the name of all the players on separate pieces of paper, placing one in each matchbox.

ARRAY
ARRAY
$team = array(Bill ','Mike','Chris','Anne');
hence we want to know who is player 2 then
echo $team[1]; //Display the name Mike

Functions used in array:

1.is_array
Arrays and variables share the same namespace.If you’re in doubt and your code needs to check whether a variable is an array.

echo (is_array($variable)) ? "Is an array" : "Is not an array"; 
Here an Undefined variable message will be generated 

2.count

Although each function and for each…as loop structure are excellent ways to walk through an array’s contents, sometimes you need to know exactly how many elements there are in your array, particularly if you will be referencing them directly.

echo count($fred);

3.sort

Sorting is so common that PHP provides a built-in function. In its simplest form, you would use it like this:

sort($fred);

4.shuffle:

There may be times when you need the elements of an array to be put in random order, such as when you’re creating a game of playing cards:

shuffle($card);

5.explode

This is a very useful function with which you can take a string containing several items separated by a single character and then place each of these items into an array.

<?php
$temp =explode(' ',"This is a sentence with seven words");
print_r($temp);
?>

6.extract:

Sometimes it can be convenient to turn the key/value pairs from an array into PHP variables. One such time might be when you are processing the $_GET or $_POST variables as sent to a PHP script by a form.

extract($_GET);

7.compact:

At times you may want to use compact, the inverse of extract, to create an array from variable and their values.

<?php
$fname="Doctor";
$sname="Who";
$planet="Gallifrey";
$system="Gridlock";
$constellation="Kasterborous";
$contact=compact('fname','sname','planet','system','constellation');
print_r($contact);
?>
OUTPUT:
Array
{
[fname]=>Doctor
[sname]=>Who
[planet]=>Gallifrey
[system]=>Gridlock
[constellation]=>Kasterborous
}

8.reset:

When for each…as construct or each function walks through an array, it keeps an internal PHP pointer that makes a note of which element of the array it should return next. If your code ever needs to return to the start of an array, you can issue reset, which also returns the value of that element

Syntax_
reset($fred);      //Throw away return value
$item=reset($fred);  //Keep first element of  the array in $item
end

As with reset, you can move PHP’s internal array pointer to the final element in an array using the end function, which also returns the value of the element, and can be used as in these examples:

end($abhi);
$item=end($fred);
Translate »