phpmysql1.3

 

Arrays

An array is a single variable that can hold more than one value at once. An array as a list of values. Each value within an array is called an element , and each element is referenced by its own index.

To access an element ’ s value — whether you ’ re creating, reading, writing, or deleting the element — you use that element ’ s index

 Creating Arrays-Accessing Array Elements

PHP — support two types of arrays:

 Indexed arrays — These are arrays where each element is referenced by a numeric index, usually starting from zero. For example, the first element has an index of 0, the second has an index of 1 …so on

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( “SriSri”, “Vishnu”, “Anand”, “Krishna” );

 In this case, the “SriSri ” element has an index of 0 , “Vishnu ” has an index of 1 , “Anand ” has an index of 2 , and “Krishna ” has an index of 3

 

Or     // Creating the same array using [] and numeric indices

$authors2[0] = “SriSri”;

$authors2[1] = “Vishnu”;

$authors2[2] = “Anand”;

$authors2[3] = “Krishna”;

 

Or    // Creating the same array using the empty [] syntax

Creating an array elements by using the array() construct with an empty list:

$authors = array();

$authors3[] = “SriSri”;

$authors3[] = “Vishnu”;

$authors3[] = “Anand”;

$authors3[] = “Krishna”;

 

Accessing Array elements

$authors = array(“SriSri”, “Vishnu”, “Anand”, “Krishna”);

$myAuthor = $authors[0];                            // $myAuthor contains “SriSri”

$anotherAuthor = $authors[1];                    // $anotherAuthor contains “Vishnu”

 

$pos = 2;

echo $authors[$pos + 1];                               //Displays “Krishna”

 

Changing Elements

For example, the following code changes the value of the third element in an indexed array from

“Anand” to “ Vikram “ :

$authors = array(“SriSri”, “Vishnu”, “Anand”, “Krishna”);

$authors[2] = “Vikram”;

 

You can just create a new element with an index of 4, as follows:

$authors[4] = “Sudha”;

 

Or        $authors[] = “Sudha”;

 

Associative arrays — This type of array is also referred to as a hash or map. With associative arrays, each element is referenced by a string index.

For example, you might create an array element representing a customer ’ s age and give it an index of “ age ”

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”=>“Wings of Fire”, “author”=>“Abdul kalam”, “pubYear”=>1999);

 

This creates an array with three elements:

“Wings of Fire” , which has an index of “ title “ ;

“Abdul kalam”, which has an index of “ author “ ;

1999 , which has an index of “ pubYear ”.

Or     // Creating an associative array using [] syntax

$myBook = array();

$myBook[“title”] = “Wings of Fire”;

$myBook[“author”] = “Abdul kalam”;

$myBook[“pubYear”] = 1999;

 

Accessing Array elements

$myBook = array( “title”=>“Wings of Fire”, “author”=>“Abdul kalam”, “pubYear”=>1999);

$myTitle = $myBook[“title”];                        // $myTitle contains “Wings of Fire”

$myAuthor = $myBook[“author”];              // $myAuthor contains “Abdul kalam”

 

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

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

$myBook[“pubYear”] = 1952;

 

Outputting an Entire Array with print_r()

Using print_r() is easy — just pass it the array you want to output:

print_r( $array );

 

print_r() displays the type of the variable it was passed — Array — followed by a list of all the elements in the array, in the form key => value . The keys (or indices) of the indexed array are 0 through 3 , and the keys of the associative array are title , author , and pubYear .

By the way, the script wraps < pre > and < /pre > tags around the output from print_r() so that you can see the formatting properly. Without these tags, the output would appear on a single line when viewed in a Web page.

<html>

<head>

<title> Outputting Arrays with print_r() </title>

<link rel=”stylesheet” type=”text/css” href=”common.css”/>

</head >

<body>

<h1 > Outputting Arrays with print_r() </h1>

<?php

$authors = array(“SriSri”, “Vishnu”, “Anand”, “Krishna”);

$myBook = array( “title”=>“Wings of Fire”,

“author”=>“Abdul kalam”,

“pubYear”=>1999);

echo ‘<h2> $authors: </h2> <pre> ’;

print_r( $authors );

echo ‘ </pre > < h2 > $myBook: </h2> <pre> ’;

print_r( $myBook );

echo “ </pre> ”;

?>

</body>

</html>

 








Extracting a Range of Elements with array_slice()

array_slice() , that you can use to extract a range of elements from an array. To use it, pass it the array to extract the slice from, followed by the position of the first element in the range (counting from zero), followed by the number of elements to extract. The function returns a new array containing copies of the elements you extracted (it doesn ’ t touch the original array).

 

$authors = array(“SriSri”, “Vishnu”, “Anand”, “Krishna”);

$authorsSlice = array_slice( $authors, 1, 2 );                       // Displays “Array ( [0] = > Vishnu [1] = > Anand )”

print_r( $authorsSlice );

 

With Associative Arrays

$myBook = array( “title”=>“Wings of Fire”,

“author”=>“Abdul kalam”,

“pubYear”=>1999);

$myBookSlice = array_slice( $myBook, 1, 2 ); // Displays “Array ( [author] = > Abdul kalam [pubYear] = > 1999 )”;

print_r( $myBookSlice );

 

Counting Elements in an Array

 

PHP count() function tells how many elements are in an array .All you need to do is pass the array to count() , and it returns the number of elements as an integer:

 

$authors = array(“SriSri”, “Vishnu”, “Anand”, “Krishna”);

$myBook = array( “title”=>“Wings of Fire”,

 “author”=>“Abdul kalam”,

“pubYear”=>1999);

 

echo count( $authors ) . “ <br/> ”;              // Displays “4”

echo count( $myBook ) . “ <br/> ”;              // Displays “3”

 

You might want to use count() to retrieve the last element of an indexed array:

$lastIndex = count( $authors ) - 1;

echo $authors[$lastIndex];                            // Displays “Krishna”

 

Stepping Through an Array







<html>

<head>

<title> Stepping Through an Array </title>

<link rel=”stylesheet” type=”text/css” href=”common.css”/>

</head >

<body >

<h1 > Stepping Through an Array </h1>

<?php

$authors = array(“SriSri”, “Vishnu”, “Anand”, “Krishna”);

echo “ <p> The array: “ . print_r( $authors, true ) . “ </p> ”;

echo “ <p> The current element is: “ . current( $authors ) . “. </p> ”;

echo “ <p> The next element is: “ . next( $authors ) . “. </p> ”;

echo “ <p> ...and its index is: “ . key( $authors ) . “. </p> ”;

echo “ <p> The next element is: “ . next( $authors ) . “. </p> ”;

echo “ <p> The previous element is: “ . prev( $authors ) . “. </p> ”;

echo “ <p> The first element is: “ . reset( $authors ) . “. </p> ”;

echo “ <p> The last element is: “ . end( $authors ) . “. </p> ”;

echo “ <p> The previous element is: “ . prev( $authors ) . “. </p> ”;

?>

</body>

</html>

 

Looping Through Arrays with foreach

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)

 

Example

$authors = array(“SriSri”, “Vishnu”, “Anand”, “Krishna”);

foreach ( $authors as $val )

{

echo $val . “ < br/ > ”;

}

SriSri

Vishnu

Anand

Krishna

 

Using foreach to Loop Through Keys and Values

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.

<?php

$myBook = array( “title”=>“Wings of Fire”,

“author”=>“Abdul kalam”,

“pubYear”=>1999);

foreach ( $myBook as $key = > $value ) {

echo “ < dt > $key < /dt > ”;

echo “ < dd > $value < /dd > ”;

}

? >

 

Working with Multidimensional Arrays

This ability of arrays to store other arrays in their elements allows  to create multidimensional arrays

 Creating a Multidimensional Array

<html>

<head >

<title > A Two-Dimensional Array </title>

<link rel=”stylesheet” type=”text/css” href=”common.css”/ >

</head>

< body>

< h1 > A Two-Dimensional Array </h1>

<?php

$myBooks =array(

array(“title”=>“The Grapes of Wrath”,

“author”=>“John Steinbeck”,

“pubYear”=>1939

),

array(

“title” = > “The Trial”,

“author” = > “Franz”,

“pubYear” = > 1925

 ),

array

(

“title” = > “The Hobbit”,

 “author” = > “J. R. R. Tolkien”,

 “pubYear” = > 1937

),

Array

(

“title” = > “A Tale of Two Cities”,

 “author” = > “Charles”,

 “pubYear” = > 1859

),

 );

echo “ <pre> ”;

print_r ( $myBooks );

echo “ </pre> ”;

?>

</body>

</html>

 
















Accessing Elements of Multidimensional Arrays

// Displays “Array ( [title]=>The Trial [author]=>Franz[pubYear]=>1925 )”;

print_r($myBooks[1] );

 

// Displays “The Trial”

echo “ <br/> ” . $myBooks[1][“title”] . “ <br/> ”;

 

// Displays “1859”

echo $myBooks[3][“pubYear”] . “ <br/> ”;

 

Manipulating Arrays

 

Sorting Arrays

PHP provides twelve functions used to sort an array.

 

Sorting Indexed Arrays with sort() and rsort()

sort() sorts the values of the array in ascending order .

rsort() sorts the values in descending order.

Here ’ s an example that sorts a list of authors alphabetically in ascending order, and then in descending order:

 

$authors = array(“SriSri”, “Vishnu”, “Anand”, “Krishna”);

sort( $authors ); 

print_r( $authors );  // Displays “Array ( [0] = > Anand [1] = > Krishna [2] = > SriSri [3] = > Vishnu)”

 

// Displays “Array ( [0] = > Vishnu [1] = > SriSri [2] = > Krishna [3] = > Anand )”

rsort( $authors );

print_r( $authors );

 

Sorting Associative Arrays with asort() and arsort()

asort() and arsort() work just like sort() and rsort() , but they preserve the association between each element ’ s key and its value:

 

$myBook = array( “title” = > “Bleak House”,

“author” = > “Dickens”,

“year” = > 1853 );

// Displays “Array ( [title] = > Bleak House [author] = > Dickens [year] = > 1853 )”

asort( $myBook );

print_r( $myBook );

// Displays “Array ( [year] = > 1853 [author] = > Dickens [title] = > Bleak House )”

arsort( $myBook );

print_r( $myBook );

 

Sorting Associative Array Keys with ksort() and krsort()

asort() and arsort() sort elements by value, ksort() and krsort() sort the elements by their keys:

 

$myBook = array( “title” = > “Bleak House”,

“author” = > “Dickens”,

“year” = > 1853 );

// Displays “Array ( [author] = > Dickens [title] = > Bleak House [year] = > 1853 )”

ksort( $myBook );

print_r( $myBook );

 

// Displays “Array ( [year] = > 1853 [title] = > Bleak House [author] = > Dickens )”

krsort( $myBook );

print_r( $myBook );

 

Multi - Sorting with array_multisort()

 

array_multisort() lets you sort multiple related arrays at the same time, preserving the relationship between the arrays. To use it, simply pass in a list of all the arrays you want to sort:

 array_multisort( $array1, $array2, ... );

 

<html>

<head>

<title> Using array_multisort() on a Two-Dimensional Array </title>

<link rel=”stylesheet” type=”text/css” href=”common.css”/>

</head>

<body>

<h1> Using array_multisort() on a Two-Dimensional Array </h1>

< ?php

$myBooks = array(

array(

“title” = > “The Grapes of Wrath”,

“author” = > “John Steinbeck”,

“pubYear” = > 1939

),

array(

“title” => “A Tale of Two Cities”,

“author” => “Charles Dickens”,

“pubYear” => 1859

),

);

array_multisort( $myBooks );

echo “ <pre> ”;

print_r( $myBooks );

echo “ </pre> ”;

?>

</body>

</html>

 
















Adding and Removing Array Elements

PHP features five useful functions that you can use to add and remove elements:

 

Adding and Removing Elements at the Start and End

array_unshift() – – Adds one or more new elements to the start of an array

 

$authors = array(“SriSri”, “Vishnu”, “Anand”, “Krishna”);

echo array_unshift( $authors, “Kalam”, “Gandhi” ) . “ < br/ > ”;                        // Displays “6”

 

array_shift() – Removes the first element from the start of an array

$myBook = array( “title” = > “The Grapes of Wrath”,

                                “author” = > “John Steinbeck”,

                                 “pubYear” = > 1939 );

echo array_shift( $myBook ) . “ <br/> ”; // Displays “The Grapes of Wrath”

 

// Displays “Array ( [author] = > John Steinbeck [pubYear] = > 1939 )”

print_r( $myBook );

 

array_push() — Adds one or more new elements to the end of an array

$authors = array(“SriSri”, “Vishnu”, “Anand”, “Krishna”);

echo array_push( $authors, “Kalam”, “Gandhi” ) . “ <br/ > ”; // Displays “6”

// Displays “Array ([0]=> SriSri[1]=>Vishnu[2]=>Anand[3]=> Krishna[4]=>Kalam[5]=> Gandhi)”

print_r( $authors );

 

array_pop() — Removes the last element from the end of an array

$myBook = array(“title”=> “The Grapes of Wrath”,

“author” => “John Steinbeck”,

“pubYear” => 1939 );

echo array_pop( $myBook ) . “ <br/> ”; // Displays “1939”

 

array_splice() — Removes element(s) from and/or adds element(s) to any point in an array

$authors = array( “SriSri”, “Vishnu”, “Anand” );

array_splice( $authors, 1, 0, array(“authorName”=>“Rishi” ));

echo “<pre>”;

print_r($authors );

echo “</pre>”;

This code produces the following result:

Array

(

[0] => Srisri

[1] => Rishi

[2] => Vishnu

[3] => Anand

)

 

Merging Arrays Together

If you want to join two or more arrays together to produce one big array, you need the array_merge()

function. This function takes one or more arrays as arguments, and returns the merged array.

 

$authors = array( “Srisri”, “Vishnu” );

$moreAuthors = array( “Anand”, “Rishi” );

// Displays “Array ( [0] = > Srisri[1] = >Vishnu[2] = >Anand[3] = >Rishi )”

print_r( array_merge( $authors, $moreAuthors));

 

Converting Between Arrays and Strings

To convert a string to an array, you can use PHP ’ s explode() string function. This function takes a string, splits it into separate chunks based on a specified delimiter string, and returns an array containing the chunks. Here ’ s an example:

 

$fruitString = “apple,pear,banana,strawberry,peach”;

$fruitArray = explode( “,”, $fruitString );

 

After running this code, $fruitArray contains an array with five string elements: “ apple ”, “ pear ”, “ banana ”, “ strawberry ”, and “ peach ”.

 

Converting an Array to a List of Variables

This construct provides an easy way to pull out the values of an array into separate variables. Consider the following code:

 

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

$title = $myBook[0];

$author = $myBook[1];

$pubYear = $myBook[2];

echo $title . “ <br/> ”; // Displays “The Grapes of Wrath”

echo $author . “ <br/> ”; // Displays “John Steinbeck”

echo $pubYear . “ <br/> ”; // Displays “1939”

 Prev Topic Strings

 

 

No comments:

Post a Comment