0% found this document useful (0 votes)
21 views

Module 2 PHP

Php

Uploaded by

Leslie Qwer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Module 2 PHP

Php

Uploaded by

Leslie Qwer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Module 2

PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.

1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and
object in the PHP array. All PHP array elements are assigned to an index number by default.

PHP indexed array can store numbers, strings or any object. PHP indexed array is also
known as numeric array.

There are two ways to define indexed array:

1st way:

1. $season=array("summer","winter","spring","autumn");

2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";

Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>

Output:

Season are: summer, winter, spring and autumn

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

2nd way:

1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";

Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

PHP Multidimensional Array


PHP multidimensional array is also known as array of arrays. It allows you to store tabular
data in an array. PHP multidimensional array can be represented in the form of matrix which
is represented by row * column.

Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );

PHP Multidimensional Array Example


Let's see a simple example of PHP multidimensional array to display following tabular data.
In this example, we are displaying 3 rows and 3 columns.

Id Name Salary

1 sonoo 400000

2 john 500000

3 rahul 300000

File: multiarray.php
1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14. }
15. ?>

Output:
1 sonoo 400000
2 john 500000
3 rahul 300000

PHP Array Functions


PHP provides various array functions to access and manipulate the elements of array. The
important PHP array functions are given below.

1) PHP array() function


PHP array() function creates and returns an array. It allows you to create indexed, associative
and multidimensional arrays.

Syntax

1. array array ([ mixed $... ] )

2. <?php
3. $season=array("summer","winter","spring","autumn");
4. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
5. ?>

Output:

Season are: summer, winter, spring and autumn

2) PHP array_change_key_case() function


PHP array_change_key_case() function changes the case of all key of an array.

Note: It changes case of key only.

Syntax

1. array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>

Output:

Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>

Output:

Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )
3) PHP array_chunk() function
PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can
divide array into many parts.

Syntax

1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

Example

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>

Output:

Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)

4) PHP count() function


PHP count() function counts all elements in an array.

Syntax

1. int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>

Output:

4
5) PHP sort() function
PHP sort() function sorts all the elements in an array.

Syntax

1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>

Output:

autumn
spring
summer
winter

6) PHP array_reverse() function


PHP array_reverse() function returns an array containing elements in reversed order.

Syntax

1. array array_reverse ( array $array [, bool $preserve_keys = false ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>

Output:

autumn
spring
winter
summer

7) PHP array_search() function


PHP array_search() function searches the specified value in an array. It returns key if search
is successful.

Syntax

1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>

Output:

8) PHP array_intersect() function


PHP array_intersect() function returns the intersection of two array. In other words, it returns
the matching elements of two array.

Syntax

1. array array_intersect ( array $array1 , array $array2 [, array $... ] )


Example

1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>

Output:

sonoo
smith

PHP - What are Classes and Objects?


Classes and objects are the two main aspects of object-oriented programming.

A class is a template for objects, and an object is an instance of class.

Define a Class
A class is defined by using the class keyword, followed by the name of the class and a pair of curly
braces ({}). All its properties and methods go inside the braces:

Syntax
<?php
class Fruit {
// code goes here...
}
?>

Below we declare a class named Fruit consisting of two properties ($name and $color) and two
methods set_name() and get_name() for setting and getting the $name property:
<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>

Define Objects
Classes are nothing without objects! We can create multiple objects from a class. Each object has all
the properties and methods defined in the class, but they will have different property values.

Objects of a class are created using the new keyword.

In the example below, $apple and $banana are instances of the class Fruit:

Example
<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit();


$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>

In the example below, we add two more methods to class Fruit, for setting and getting the $color
property:

Example
<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}

$apple = new Fruit();


$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>
PHP - The $this Keyword
The $this keyword refers to the current object, and is only available inside methods.

Look at the following example:

Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>

So, where can we change the value of the $name property? There are two ways:

1. Inside the class (by adding a set_name() method and use $this):

Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");

echo $apple->name;
?>

2. Outside the class (by directly changing the property value):

Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";

echo $apple->name;
?>

PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific class:

Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>

PHP - The __construct Function


A constructor allows you to initialize an object's properties upon creation of the object.

If you create a __construct() function, PHP will automatically call this function when you create an
object from a class.

Notice that the construct function starts with two underscores (__)!

<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>
Try it Yourself »
<?php
class Fruit {
public $name;
public $color;

function __construct($name, $color) {


$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}

$apple = new Fruit("Apple", "red");


echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>

PHP - The __destruct Function


A destructor is called when the object is destructed or the script is stopped or exited.

If you create a __destruct() function, PHP will automatically call this function at the end of the script.

Notice that the destruct function starts with two underscores (__)!

<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}

$apple = new Fruit("Apple");


?>

<?php
class Fruit {
public $name;
public $color;

function __construct($name, $color) {


$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

PHP - Access Modifiers


Properties and methods can have access modifiers which control where they can be accessed.

There are three access modifiers:

 public - the property or method can be accessed from everywhere. This is default
 protected - the property or method can be accessed within the class and by classes derived
from that class
 private - the property or method can ONLY be accessed within the class

In the following example we have added three different access modifiers to three properties (name,
color, and weight). Here, if you try to set the name property it will work fine (because the name
property is public, and can be accessed from everywhere). However, if you try to set the color or
weight property it will result in a fatal error (because the color and weight property are protected and
private):

ExampleGet your own PHP Server


<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>

In the next example we have added access modifiers to two functions. Here, if you try to call the
set_color() or the set_weight() function it will result in a fatal error (because the two functions are
considered protected and private), even if all the properties are public:

Example
<?php
class Fruit {
public $name;
public $color;
public $weight;

function set_name($n) { // a public function (default)


$this->name = $n;
}
protected function set_color($n) { // a protected function
$this->color = $n;
}
private function set_weight($n) { // a private function
$this->weight = $n;
}
}

$mango = new Fruit();


$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>

PHP - What is Inheritance?


Inheritance in OOP = When a class derives from another class.

The child class will inherit all the public and protected properties and methods from the parent class.
In addition, it can have its own properties and methods.
An inherited class is defined by using the extends keyword.

<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

// Strawberry is inherited from Fruit


class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>

Example Explained
The Strawberry class is inherited from the Fruit class.

This means that the Strawberry class can use the public $name and $color properties as well as the
public __construct() and intro() methods from the Fruit class because of inheritance.

The Strawberry class also has its own method: message().

PHP - Inheritance and the Protected Access


Modifier
In the previous chapter we learned that protected properties or methods can be accessed within the
class and by classes derived from that class
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

class Strawberry extends Fruit {


public function message() {
echo "Am I a fruit or a berry? ";
}
}

// Try to call all three methods from outside class


$strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public
$strawberry->message(); // OK. message() is public
$strawberry->intro(); // ERROR. intro() is protected
?>

In the example above we see that if we try to call a protected method (intro()) from outside the class,
we will receive an error. public methods will work fine!

<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

class Strawberry extends Fruit {


public function message() {
echo "Am I a fruit or a berry? ";
// Call protected method from within derived class - OK
$this -> intro();
}
}

$strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public


$strawberry->message(); // OK. message() is public and it calls intro() (which is protected) from
within the derived class
?>

PHP - Overriding Inherited Methods


Inherited methods can be overridden by redefining the methods (use the same name) in the child
class.

Look at the example below. The __construct() and intro() methods in the child class (Strawberry)
will override the __construct() and intro() methods in the parent class (Fruit):

Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

class Strawberry extends Fruit {


public $weight;
public function __construct($name, $color, $weight) {
$this->name = $name;
$this->color = $color;
$this->weight = $weight;
}
public function intro() {
echo "The fruit is {$this->name}, the color is {$this->color}, and the weight is {$this->weight}
gram.";
}
}

$strawberry = new Strawberry("Strawberry", "red", 50);


$strawberry->intro();
?>

PHP - The final Keyword


The final keyword can be used to prevent class inheritance or to prevent method overriding.

The following example shows how to prevent class inheritance:

Example
<?php
final class Fruit {
// some code
}

// will result in error


class Strawberry extends Fruit {
// some code
}
?>

The following example shows how to prevent method overriding:

<?php
class Fruit {
final public function intro() {
// some code
}
}

class Strawberry extends Fruit {


// will result in error
public function intro() {
// some code
}
}
?>

PHP - Class Constants


Class constants can be useful if you need to define some constant data within a class.

A class constant is declared inside a class with the const keyword.

A constant cannot be changed once it is declared.

Class constants are case-sensitive. However, it is recommended to name the constants in all
uppercase letters.

We can access a constant from outside the class by using the class name followed by the scope
resolution operator (::) followed by the constant name, like here:

<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
}

echo Goodbye::LEAVING_MESSAGE;
?>

Or, we can access a constant from inside the class by using the self keyword followed by the scope
resolution operator (::) followed by the constant name, like here:

<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
public function byebye() {
echo self::LEAVING_MESSAGE;
}
}

$goodbye = new Goodbye();


$goodbye->byebye();
?>

PHP - What are Abstract Classes and Methods?


Abstract classes and methods are when the parent class has a named method, but need its child
class(es) to fill out the tasks.

An abstract class is a class that contains at least one abstract method. An abstract method is a method
that is declared, but not implemented in the code.

An abstract class or method is defined with the abstract keyword:

<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
}
?>

When inheriting from an abstract class, the child class method must be defined with the same name,
and the same or a less restricted access modifier. So, if the abstract method is defined as protected,
the child class method must be defined as either protected or public, but not private. Also, the type
and number of required arguments must be the same. However, the child classes may have optional
arguments in addition.

So, when a child class is inherited from an abstract class, we have the following rules:

 The child class method must be defined with the same name and it redeclares the parent
abstract method
 The child class method must be defined with the same or a less restricted access modifier
 The number of required arguments must be the same. However, the child class may have
optional arguments in addition

PHP - What are Interfaces?


Interfaces allow you to specify what methods a class should implement.

Interfaces make it easy to use a variety of different classes in the same way. When one or more
classes use the same interface, it is referred to as "polymorphism".

Interfaces are declared with the interface keyword:

<?php
interface InterfaceName {
public function someMethod1();
public function someMethod2($name, $color);
public function someMethod3() : string;
}
?>

PHP - Interfaces vs. Abstract Classes


Interface are similar to abstract classes. The difference between interfaces and abstract classes are:

 Interfaces cannot have properties, while abstract classes can


 All interface methods must be public, while abstract class methods is public or protected
 All methods in an interface are abstract, so they cannot be implemented in code and the
abstract keyword is not necessary
 Classes can implement an interface while inheriting from another class at the same time

PHP - Using Interfaces


To implement an interface, a class must use the implements keyword.

A class that implements an interface must implement all of the interface's methods.

<?php
interface Animal {
public function makeSound();
}

class Cat implements Animal {


public function makeSound() {
echo "Meow";
}
}

$animal = new Cat();


$animal->makeSound();
?>

Using interfaces, we can write some code which can work for all of the animals even if each animal
behaves differently:

Example
<?php
// Interface definition
interface Animal {
public function makeSound();
}

// Class definitions
class Cat implements Animal {
public function makeSound() {
echo " Meow ";
}
}

class Dog implements Animal {


public function makeSound() {
echo " Bark ";
}
}

class Mouse implements Animal {


public function makeSound() {
echo " Squeak ";
}
}

// Create a list of animals


$cat = new Cat();
$dog = new Dog();
$mouse = new Mouse();
$animals = array($cat, $dog, $mouse);

// Tell the animals to make a sound


foreach($animals as $animal) {
$animal->makeSound();
}
?>

PHP - What are Traits?


PHP only supports single inheritance: a child class can inherit only from one single parent.

So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and
abstract methods that can be used in multiple classes, and the methods can have any access modifier
(public, private, or protected).
Traits are declared with the trait keyword:

<?php
trait TraitName {
// some code...
}
?>

To use a trait in a class, use the use keyword:

Syntax
<?php
class MyClass {
use TraitName;
}
?>

Let's look at an example:

Example
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}

class Welcome {
use message1;
}

$obj = new Welcome();


$obj->msg1();
?>

Example Explained
Here, we declare one trait: message1. Then, we create a class: Welcome. The class uses the trait, and
all the methods in the trait will be available in the class.
If other classes need to use the msg1() function, simply use the message1 trait in those classes. This
reduces code duplication, because there is no need to redeclare the same method over and over again.

PHP - Static Methods


Static methods can be called directly - without creating an instance of the class first.

Static methods are declared with the static keyword:

<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>

To access a static method use the class name, double colon (::), and the method name:

Syntax
ClassName::staticMethod();

Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}

// Call static method


greeting::welcome();
?>

Example Explained
Here, we declare a static method: welcome(). Then, we call the static method by using the class
name, double colon (::), and the method name (without creating an instance of the class first).

PHP - More on Static Methods


A class can have both static and non-static methods. A static method can be accessed from a method
in the same class using the self keyword and double colon (::):

Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}

public function __construct() {


self::welcome();
}
}

new greeting();
?>

Static methods can also be called from methods in other classes. To do this, the static method should
be public:

To call a static method from a child class, use the parent keyword inside the child class. Here, the
static method can be public or protected.

PHP - Static Properties


Static properties can be called directly - without creating an instance of a class.

Static properties are declared with the static keyword:

<?php
class ClassName {
public static $staticProp = "W3Schools";
}
?>

To access a static property use the class name, double colon (::), and the property name:

Syntax
ClassName::$staticProp;

Let's look at an example:


Example
<?php
class pi {
public static $value = 3.14159;
}

// Get static property


echo pi::$value;
?>

Example Explained
Here, we declare a static property: $value. Then, we echo the value of the static property by using the
class name, double colon (::), and the property name (without creating a class first).

PHP - More on Static Properties


A class can have both static and non-static properties. A static property can be accessed from a
method in the same class using the self keyword and double colon (::):

Example
<?php
class pi {
public static $value=3.14159;
public function staticValue() {
return self::$value;
}
}

$pi = new pi();


echo $pi->staticValue();
?>

PHP Namespaces
Namespaces are qualifiers that solve two different problems:

1. They allow for better organization by grouping classes that work together to perform a task
2. They allow the same name to be used for more than one class
For example, you may have a set of classes which describe an HTML table, such as Table, Row and
Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed.
Namespaces can be used to organize the classes into two different groups while also preventing the
two classes Table and Table from being mixed up.

Declaring a Namespace
Namespaces are declared at the beginning of a file using the namespace keyword:

Declare a namespace called Html:

<?php
namespace Html;
?>

A namespace declaration must be the first thing in the PHP file. The following code would be
invalid:

<?php
echo "Hello World!";
namespace Html;
...
?>

Constants, classes and functions declared in this file will belong to the Html namespace:

Example
Create a Table class in the Html namespace:

<?php
namespace Html;
class Table {
public $title = "";
public $numRows = 0;
public function message() {
echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
}
}
$table = new Table();
$table->title = "My table";
$table->numRows = 5;
?>

<!DOCTYPE html>
<html>
<body>

<?php
$table->message();
?>

</body>
</html>

For further organization, it is possible to have nested namespaces:

Syntax
Declare a namespace called Html inside a namespace called Code:

<?php
namespace Code\Html;
?>

Using Namespaces
Any code that follows a namespace declaration is operating inside the namespace, so classes that
belong to the namespace can be instantiated without any qualifiers. To access classes from outside a
namespace, the class needs to have the namespace attached to it.

Example
Use classes from the Html namespace:

<?php
$table = new Html\Table();
$row = new Html\Row();
?>

When many classes from the same namespace are being used at the same time, it is easier to use
the namespace keyword:
Example
Use classes from the Html namespace without the need for the Html\qualifier:

<?php
namespace Html;
$table = new Table();
$row = new Row();
?>

PHP - What is an Iterable?


An iterable is any value which can be looped through with a foreach() loop.

The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function
arguments and function return values.

PHP - Using Iterables


The iterable keyword can be used as a data type of a function argument or as the return type of a
function:

ExampleGet your own PHP Server


Use an iterable function argument:

<?php
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}

$arr = ["a", "b", "c"];


printIterable($arr);
?>

PHP - Creating Iterables


Arrays

All arrays are iterables, so any array can be used as an argument of a function that requires an
iterable.

Iterators

Any object that implements the Iterator interface can be used as an argument of a function that
requires an iterable.

An iterator contains a list of items and provides methods to loop through them. It keeps a pointer to
one of the elements in the list. Each item in the list should have a key which can be used to find the
item.

An iterator must have these methods:

 current() - Returns the element that the pointer is currently pointing to. It can be any data
type
 key() Returns the key associated with the current element in the list. It can only be an integer,
float, boolean or string
 next() Moves the pointer to the next element in the list
 rewind() Moves the pointer to the first element in the list
 valid() If the internal pointer is not pointing to any element (for example, if next() was called
at the end of the list), this should return false. It returns true in any other case

You might also like