Thursday 23 January 2020

BSCCS UNIT – II: Chapter 4 - Array


UNIT – II: Chapter 4 - Array
4.1 Anatomy of an Array
4.2 Creating index based and Associative array
4.3 Accessing array Element
4.4 Looping with Index based array
4.5 Looping with associative array using foreach()
4.1 Anatomy of an Array
There are three different kind of arrays:
·        Numeric array - An array with a numeric index. Values are stored and accessed in linear fashion
·        Associative array - An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
·        Multidimensional array - An array containing one or more arrays and values are accessed using multiple indices

4.2 Creating index based and Associative array:
Arrays in PHP are easy to create. The simplest way to create a new array variable is to use PHP s built - in array() construct. This takes a list of values and creates an array containing those values, which you can then assign to a variable:

$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );

In this line of code, an array of four elements is created, with each element containing a string value. The array is then assigned to the variable $authors.
You can now access any of the array elements via the single variable name, $authors. This array is an indexed array, which means that each of the array elements is accessed via its own numeric index, starting at zero.
Here, the “Steinbeck” element has an index of 0 , “ Kafka ” has an index of 1 , “ Tolkien ” has an index of 2 , and “ Dickens ” has an index of 3 .

If you want to create an associative array, where each element is identified by a string index rather than a number, you need to use the => operator, as follows:

$myBook = array( “title” = > “The Grapes of Wrath”, “author” = > “John Steinbeck”, “pubYear” = > 1939 );

This creates an array with three elements: “ The Grapes of Wrath ” , which has an index of “ title “ ; “ John Steinbeck ”, which has an index of “ author “ ; and 1939 , which has an index of “ pubYear ”.

4.3 Accessing Array Elements:
Once you’ve created your array, how do you access the individual values inside it? In fact, you do this in much the same way as you access the individual characters within a string:

$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$myAuthor = $authors[0]; // $myAuthor contains “Steinbeck”
$anotherAuthor = $authors[1]; // $anotherAuthor contains “Kafka”

In other words, you write the variable name, followed by the index of the element in square brackets. If you want to access the elements of an associative array, simply use string indices rather than numbers:
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );
$myTitle = $myBook[“title”]; // $myTitle contains “The Grapes of Wrath”
$myAuthor = $myBook[“author”]; // $myAuthor contains “Steinbeck”

You don’t have to use literal values within the square brackets; you can use any expression, as long as it
evaluates to an integer or string as appropriate:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$pos = 2;
echo $authors[$pos + 1]; // Displays “Dickens”

Changing Elements
In addition to accessing the array values you can change values using the same techniques.
For example, the following code changes the value of the third element in an indexed array from “ Tolkien ” to “ Melville “ :

$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authors[2] = “Melville”;

What if you wanted to add a fifth author? You can just create a new element with an index of 4,
as follows:

$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authors[4] = “Orwell”;

There’s an even easier way to add a new element to an array — simply use square brackets with no index:

$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$authors[] = “Orwell”;

When you do this, PHP knows that you want to add a new element to the end of the array, and it automatically assigns the next available index — in this case, 4 — to the element.

In fact, you can create an array from scratch simply by creating its elements using the square bracket syntax. The following three examples all produce exactly the same array:

// Creating an array using the array() construct
$authors1 = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
// Creating the same array using [] and numeric indices
$authors2[0] = “Steinbeck”;
$authors2[1] = “Kafka”;
$authors2[2] = “Tolkien”;
$authors2[3] = “Dickens”;
// Creating the same array using the empty [] syntax
$authors3[] = “Steinbeck”;
$authors3[] = “Kafka”;
$authors3[] = “Tolkien”;
$authors3[] = “Dickens”;

However, just as with regular variables, you should make sure your arrays are initialized properly first. In the second and third examples, if the $authors2 or $authors3 array variables already existed and contained other elements, the final arrays might end up containing more than just the four elements you assigned.

This creates an array with no elements (an empty array).

$authors = array();

You can then go ahead and add elements later:

$authors[] = “Steinbeck”;
$authors[] = “Kafka”;
$authors[] = “Tolkien”;
$authors[] = “Dickens”;

You can also add and change elements of associative arrays using square bracket syntax. Here an associative array is populated in two ways: first using the array() construct, and second using the
square bracket syntax:

// Creating an associative array using the array() construct
$myBook = array( “title” = > “The Grapes of Wrath”,
“author” = > “John Steinbeck”,
“pubYear” = > 1939 );

// Creating the same array using [] syntax
$myBook = array();
$myBook[“title”] = “The Grapes of Wrath”;
$myBook[“author”] = “John Steinbeck”;
$myBook[“pubYear”] = 1939;

Changing elements of associative arrays works in a similar fashion to indexed arrays:

$myBook[“title”] = “East of Eden”;
$myBook[“pubYear”] = 1952;

Outputing Array using print_r():
The print_r() function is a built-in function in PHP and is used to print or display information stored in a variable.
Syntax:
print_r( $variable, $isStore )

·        $variable: This parameter specifies the variable to be printed and is a mandatory parameter.
·        $isStore: This an option parameter. This parameter is of boolean type whose default value is FALSE and is used to store the output of the print_r() function in a variable rather than printing it. If this parameter is set to TRUE then the print_r() function will return the output which it is supposed to print.

<?php

# the print_r() function

// string variable
$var1 = "Welcome to IT";
// integer variable
$var2 = 92;

// array variable
$arr = array('0' => "Welcome", '1' => "to", '2' => "IT");

// printing the variables
print_r($var1);
echo"\n";
print_r($var2);
echo"\n";
print_r($arr);

?>

<?php

# PHP program to illustrate the print_r()  function when $isStore is set to true

# array variable
$arr = array('0' => "Welcome", '1' => "to", '2' => "IT");
                                                                          
# storing output of print_r() function in another variable
$results = print_r($arr, true);

echo $results;

?>

Extracting a Range of Elements with array_slice():
The array_slice() function returns selected parts of an array. In other words the array_slice() is an inbuilt function of PHP and is used to fetch a part of an array by slicing through it, according to the users choice.
Syntax:
array_slice($array, $start_point, $slicing_range, preserve)
$array (mandatory): This parameter refers to the original array, we want to slice.
$start_point (mandatory): This parameter refers to the starting position of the array from where the slicing need to be performed. It is mandatory to supply this value. If the value supplied is negative, then the function starts slicing from the end of the array, i.e., -1 refers to the last element of the array.
$slicing _range (optional): This parameter refers to the range or limit point upto which the slicing is needed to be done. A negative value will indicate the count from the end of the string. Now, this can also be left blank. On leaving blank the function will slice through all the values as mentioned in the starting point right up to the end.
preserve (optional): This parameter can take only two boolean parameters, i.e., either True or False. This will tell the function whether to preserve the keys or reset it. True refers to preserve the keys and false refers to reset the keys. False being the default value.

<?php

// PHP program to illustrate the
// array_slice() function

// Input array
$array = array("Rajesh", "krishna", "Rahul",
                                                                                          "Nandu", "Bhairav");
                                                                                         
// Slice from pos 1 to pos 3                                                                                       
print_r(array_slice($array, 1, 3, true));

?>

count():
The count() function returns the number of elements in an array.
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>

Numeric Array:
These arrays can store numbers, strings and any object but their index will be prepresented by numbers. By default, array index starts from zero.
Example:
Following is the example showing how to create and access numeric arrays. Here we have used array() function to create array.
 
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
  echo "Value is $value <br />";
}
 
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
 
foreach( $numbers as $value )
{
  echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

Associative Arrays:
The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.
NOTE: Don't keep associative array inside double quote while printing otherwise it would not return any value.
Example:
<html>
<body>
<?php
# First method to associate create array.
$salaries = array(
                                 "mohammad" => 2000,
                                 "qadir" => 1000,
   "zara" => 500
                                );

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
echo "Salary of zara is ".  $salaries['zara']. "<br />";

# Second method to create array.
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
echo "Salary of zara is ".  $salaries['zara']. "<br />";
?>
</body>
</html>

This will produce following result:
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
Multidimensional Arrays:
A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
   $marks = array(
                              "mohammad" => array
                              (
                              "physics" => 35,    
                              "maths" => 30,       
                              "chemistry" => 39                
                              ),
                              "qadir" => array
                (
                "physics" => 30,
                "maths" => 32,
                "chemistry" => 29
                ),
                "zara" => array
                (
                "physics" => 31,
                "maths" => 22,
                "chemistry" => 39
                )
                    );
   /* Accessing multi-dimensional array values */
   echo "Marks for mohammad in physics : " ;
   echo $marks['mohammad']['physics'] . "<br />";
   echo "Marks for qadir in maths : ";
   echo $marks['qadir']['maths'] . "<br />";
   echo "Marks for zara in chemistry : " ;
   echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
4.4 Looping with Index based array
foreach is a special kind of looping statement that works only on arrays (and objects). You can use it in two ways. You can either retrieve just the value of each element, or you can retrieve the element’s key and value.
Using foreach to Loop Through Values
The simplest way to use foreach is to retrieve each element’s value, as follows:
foreach ( $array as $value ) {
// (do something with $value here)
}
// (rest of script here)
As you might imagine, the foreach loop continues to iterate until it has retrieved all the values in the array, from the first element to the last. On each pass through the loop, the $value variable gets set to the value of the current element. You can then do whatever you need to do with the value within the loop’s code block. Then, the loop repeats again, getting the next value in the array, and so on.
Example:
<?php
$authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens" );
foreach ( $authors as $val ) {
echo $val . "</br>";
}
?>
This code displays:
Steinbeck
Kafka
Tolkien
Dickens
You can use any variable name you like to store the value. Essentially, any variable that you place after the as in the foreach statement gets assigned the current element’s value.
4.5 Looping with associative array using foreach():

To use foreach to retrieve both keys and values, use the following syntax:
foreach ( $array as $key = > $value ) {
// (do something with $key and/or $value here
}
// (rest of script here)
This behaves exactly like the previous foreach construct; the only difference is that the element’s key is also stored in the $key variable. (Again, you can use any variable names you like; they don ’ t have to be
$key and $value .)

<?php
#Declare an associative array
$aso_arr = array(
               "Up"=>"North",
               "Down"=>"South",
               "Left"=>"West",
               "Right"=>"East"
);
#Use foreach loop to traverse each elements of array and display its key and value
foreach($aso_arr as $side=>$direc) {
               echo $side . " => " . $direc . "\n";
}
?>


No comments:

Post a Comment