Home > Article > Backend Development > What is the difference between arrays and objects in PHP?
In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values are passed and object references are passed.
Array
An array is an ordered collection where elements are accessed by index. In PHP, arrays are represented using square brackets []
, with elements separated by commas.
Create array
$array = ['foo', 'bar', 'baz'];
Access elements
echo $array[0]; // 输出 "foo"
Modify elements
$array[0] = 'new value';
Object
Object is an entity with properties and methods. In PHP, objects are created using the new
keyword, followed by the class name.
Create object
$object = new stdClass();
Add attributes
$object->name = 'John Doe';
Call method
echo $object->getName(); // 输出 "John Doe"
Difference
Characteristics | Array | Object |
---|---|---|
Yes | No | |
Numeric value, string, other array | Any content | |
Index | Properties/Methods | |
Value passing | Reference passing |
Loop through the array
foreach ($array as $element) {
echo $element . '<br>';
}
foreach ($object as $property => $value) {
echo "$property: $value<br>";
}
The above is the detailed content of What is the difference between arrays and objects in PHP?. For more information, please follow other related articles on the PHP Chinese website!