PHP as Keyword
Example
Using as in a foreach loop:
$list = [1, 2, 3, 4];
foreach($list as $item) {
echo $item;
echo "<br>";
}
?>
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:
$people = [
"Peter" => "35",
"Ben" => "37",
"Joe" => "43"
];
foreach($people as $person => $age) {
echo "$person is $age years old";
echo "<br>";
}
?>
Example
Using as to give an alias to the method of a trait:
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
class Welcome {
use message1 {
message1::msg1 as msg;
}
}
$obj = new Welcome();
$obj->msg();
?>
Example
Using as to give an alias to a namespace:
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