[go: up one dir, main page]

0% found this document useful (0 votes)
22 views12 pages

Unit 2

The document discusses different types of arrays in PHP including indexed arrays, associative arrays, and multidimensional arrays. Indexed arrays use numeric indexes to store elements linearly. Associative arrays use named keys to store elements in a non-linear fashion. Multidimensional arrays store other arrays as elements, allowing elements to be accessed using multiple indices. Functions for manipulating arrays like implode(), explode(), extract(), and array_flip() are also covered.

Uploaded by

sonavanepranitee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views12 pages

Unit 2

The document discusses different types of arrays in PHP including indexed arrays, associative arrays, and multidimensional arrays. Indexed arrays use numeric indexes to store elements linearly. Associative arrays use named keys to store elements in a non-linear fashion. Multidimensional arrays store other arrays as elements, allowing elements to be accessed using multiple indices. Functions for manipulating arrays like implode(), explode(), extract(), and array_flip() are also covered.

Uploaded by

sonavanepranitee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

PHP Indexed Arrays

In indexed arrays each item has an index number.

By default, the first item has index 0, the second item has item 1, etc.

Example
Create and display an indexed array:

$cars = array("Volvo", "BMW", "Toyota");

var_dump($cars);

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

Example
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

var_dump($car);

PHP - Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep. However, arrays more than three levels deep are hard to
manage for most people.

The dimension of an array indicates the number of indices you need


to select an element.

 For a two-dimensional array you need two indices to select an element


 For a three-dimensional array you need three indices to select an
element

 We can store the data from the table above in a two-dimensional


array, like this:
 $cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

PHP implode() Function


Definition and Usage
The implode() function returns a string from the elements of an array.

Note: The implode() function accept its parameters in either order. However,
for consistency with explode(), you should use the documented order of
arguments.

Note: The separator parameter of implode() is optional. However, it is


recommended to always use two parameters for backwards compatibility.

Note: This function is binary-safe.

<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>

Syntax
implode(separator,array)

PHP explode() Function


ExampleGet your own PHP Server
Break a string into an array:

<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>

Definition and Usage


The explode() function breaks a string into an array.
Note: The "separator" parameter cannot be an empty string.

Note: This function is binary-safe.

Syntax
explode(separator,string,limit)

<!DOCTYPE html>

<html>

<body>

PHP array_flip() Function


Definition and Usage
The array_flip() function flips/exchanges all keys with their associated values
in an array.

Syntax
array_flip(array)

<?php

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");

$result=array_flip($a1);

print_r($result);

?>

</body>
</html>

Output

Array ( [red] => a [green] => b [blue] => c [yellow] => d )

PHP extract() Function


ExampleGet your own PHP Server
Assign the values "Cat", "Dog" and "Horse" to the variables $a, $b and $c:

<?php
$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "\$a = $a; \$b = $b; \$c = $c";
?>

Definition and Usage


The extract() function imports variables into the local symbol table from an
array.

This function uses array keys as variable names and values as variable
values. For each element it will create a variable in the current symbol table.

This function returns the number of variables extracted on success.

Syntax
extract(array, extract_rules, prefix)

<!DOCTYPE html>

<html>

<body>

<?php
$a = "Original";

$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");

extract($my_array);

echo "\$a = $a; \$b = $b; \$c = $c";

?>

</body>

</html>

$a = Cat; $b = Dog; $c = Horse

Arrays in PHP is a type of data structure that allows us to store multiple elements of
similar data type under a single variable thereby saving us the effort of creating a
different variable for every data. The arrays are helpful to create a list of elements of
similar types, which can be accessed using their index or key. Suppose we want to
store five names and print them accordingly. This can be easily done by the use of
five different string variables. But if instead of five, the number rises to a hundred,
then it would be really difficult for the user or developer to create so many different
variables. Here array comes into play and helps us to store every element within a
single variable and also allows easy access using an index or a key. An array is
created using an array() function in PHP.
There are basically three types of arrays in PHP:
Indexed or Numeric Arrays: An array with a numeric index where
values are stored linearly.
 Associative Arrays: An array with a string index where instead of linear
storage, each value can be assigned a specific key.
 Multidimensional Arrays: An array which contains single or multiple
array within it and can be accessed via multiple indices.
Indexed or Numeric Arrays
These type of arrays can be used to store any type of elements, but an index is
always a number. By default, the index starts at zero. These arrays can be created in
two different ways as shown in the following example:

<?php
// One way to create an indexed array

$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");

// Accessing the elements directly

echo "Accessing the 1st array elements directly:\n";

echo $name_one[2], "\n";

echo $name_one[0], "\n";

echo $name_one[4], "\n";

// Second way to create an indexed array

$name_two[0] = "ZACK";

$name_two[1] = "ANTHONY";

$name_two[2] = "RAM";

$name_two[3] = "SALIM";

$name_two[4] = "RAGHAV";

// Accessing the elements directly

echo "Accessing the 2nd array elements directly:\n";

echo $name_two[2], "\n";

echo $name_two[0], "\n";

echo $name_two[4], "\n";

?>

Output:
Accessing the 1st array elements directly:
Ram
Zack
Raghav
Accessing the 2nd array elements directly:
RAM
ZACK
RAGHAV
Traversing: We can traverse an indexed array using loops in PHP. We can loop
through the indexed array in two ways. First by using for loop and secondly by using
foreach. You can refer to PHP | Loops for the syntax and basic use.
Example:

 PHP
<?php

// One way to create an associative array

$name_one = array("Zack"=>"Zara", "Anthony"=>"Any",

"Ram"=>"Rani", "Salim"=>"Sara",

"Raghav"=>"Ravina");

// Second way to create an associative array

$name_two["zack"] = "zara";

$name_two["anthony"] = "any";

$name_two["ram"] = "rani";

$name_two["salim"] = "sara";

$name_two["raghav"] = "ravina";

// Accessing the elements directly

echo "Accessing the elements directly:\n";

echo $name_two["zack"], "\n";

echo $name_two["salim"], "\n";

echo $name_two["anthony"], "\n";

echo $name_one["Ram"], "\n";

echo $name_one["Raghav"], "\n";

?>
Output:
Looping using foreach:
Zack
Anthony
Ram
Salim
Raghav

The number of elements is 5


Looping using for:
ZACK
ANTHONY
RAM
SALIM
RAGHAV
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage,
every value can be assigned with a user-defined key of string type.
Example:

 PHP
<?php

// Creating an Associative Array

$name_one = [

"Zack" => "Zara",

"Anthony" => "Any",

"Ram" => "Rani",

"Salim" => "Sara",

"Raghav" => "Ravina",

];
// Looping through an array using foreach

echo "Looping using foreach: \n";

foreach ($name_one as $val => $val_value) {

echo "Husband is " . $val . " and Wife is " . $val_value . "\n";

// Looping through an array using for

echo "\nLooping using for: \n";

$keys = array_keys($name_one);

$round = count($name_one);

for ($i = 0; $i < $round; ++$i) {

echo $keys[$i] . " " . $name_one[$keys[$i]] . "\n";

?>

Output:
Accessing the elements directly:
zara
sara
any
Rani
Ravina
Traversing Associative Arrays: We can traverse associative arrays in a similar way
did in numeric arrays using loops. We can loop through the associative array in two
ways. First by using for loop and secondly by using foreach. You can refer to PHP |
Loops for the syntax and basic use.
Example:

 PHP
<?php
// Defining a multidimensional array

$favorites = array(

array(

"name" => "Dave Punk",

"mob" => "5689741523",

"email" => "davepunk@gmail.com",

),

array(

"name" => "Monty Smith",

"mob" => "2584369721",

"email" => "montysmith@gmail.com",

),

array(

"name" => "John Flinch",

"mob" => "9875147536",

"email" => "johnflinch@gmail.com",

);

// Accessing elements

echo "Dave Punk email-id is: " . $favorites[0]["email"], "\n";

echo "John Flinch mobile number is: " . $favorites[2]["mob"];

?>

Output:
Looping using foreach:
Husband is Zack and Wife is Zara
Husband is Anthony and Wife is Any
Husband is Ram and Wife is Rani
Husband is Salim and Wife is Sara
Husband is Raghav and Wife is Ravina

Looping using for:


zack zara
anthony any
ram rani
salim sara
raghav ravina
Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index
instead of a single element. In other words, we can define multi-dimensional arrays
as an array of arrays. As the name suggests, every element in this array can be an
array and they can also hold other sub-arrays within. Arrays or sub-arrays in
multidimensional arrays can be accessed using multiple dimensions.
Example:

 PHP

 <?php
 // Defining a multidimensional array
 $favorites = array(
 "Dave Punk" => array(
 "mob" => "5689741523",
 "email" => "davepunk@gmail.com",
 ),
 "Dave Punk" => array(
 "mob" => "2584369721",
 "email" => "montysmith@gmail.com",
 ),
 "John Flinch" => array(
 "mob" => "9875147536",
 "email" => "johnflinch@gmail.com",
 )
 );

 // Using for and foreach in nested form
 $keys = array_keys($favorites);
 for($i = 0; $i < count($favorites); $i++) {
 echo $keys[$i] . "\n";
 foreach($favorites[$keys[$i]] as $key => $value) {
 echo $key . " : " . $value . "\n";
 }
 echo "\n";
 }

 ?>

Output:
Dave Punk email-id is: davepunk@gmail.com
John Flinch mobile number is: 9875147536
Traversing Multidimensional Arrays: We can traverse through the multidimensional array
using for and foreach loop in a nested way. That is, one for loop for the outer array and one
for loop for the inner array.
Example:
Output:
Dave Punk
mob : 2584369721
email : montysmith@gmail.com

John Flinch
mob : 9875147536
email : johnflinch@gmail.com

PHP is a server-side scripting language designed specifically for web development. You can
learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

You might also like