PHP as Keyword
Example
Using as
in a foreach
loop:
<?php
$list = [1, 2, 3, 4];
foreach($list as $item) {
echo $item;
echo "<br>";
}
?>
Try it Yourself »
Definition and Usage
The as
keyword is used by the foreach
loop to establish which variables contain the key and value of an element.
The as
keyword can also be used by namespaces and traits to give them an alias.
Related Pages
The foreach
keyword.
The trait
keyword.
The use
keyword.
Read more about loops in our PHP Loops Tutorial.
Read more about traits in our PHP OOP - Traits Tutorial.
More Examples
Example
Using as
in a foreach
loop to traverse an associative array:
<?php
$people = [
"Peter" => "35",
"Ben" => "37",
"Joe" => "43"
];
foreach($people as $person => $age) {
echo "$person is $age years old";
echo
"<br>";
}
?>
Try it Yourself »
Example
Using as
to give an alias to the method of a trait
:
<?php
trait message1 {
public function msg1() {
echo
"OOP is fun! ";
}
}
class Welcome {
use message1
{
message1::msg1 as msg;
}
}
$obj = new Welcome();
$obj->msg();
?>
Try it Yourself »
Example
Using as
to give an alias to a namespace
:
<?php
namespace Html;
class Table {
public $title = "";
public $numRows = 0;
public function message() {
echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
}
}
use \Html as H;
$table = new H\Table();
$table->title = "My table";
$table->numRows = 5;
$table->message();
?>
❮ PHP Keywords
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.