Home > Backend Development > PHP Tutorial > What is the difference between arrays and objects in PHP?

What is the difference between arrays and objects in PHP?

WBOY
Release: 2024-04-29 14:39:01
Original
806 people have browsed it

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.

数组和对象在 PHP 中的区别是什么?

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'];
Copy after login

Access elements

echo $array[0]; // 输出 "foo"
Copy after login

Modify elements

$array[0] = 'new value';
Copy after login

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();
Copy after login

Add attributes

$object->name = 'John Doe';
Copy after login

Call method

echo $object->getName(); // 输出 "John Doe"
Copy after login

Difference

##OrderingYesNoTypeNumeric value, string, other arrayAny contentAccess methodIndexProperties/MethodsReference TypeValue passingReference passing
CharacteristicsArrayObject
##Practical case

Loop through the array

foreach ($array as $element) {
  echo $element . '<br>';
}
Copy after login

Loop through the object properties

foreach ($object as $property => $value) {
  echo "$property: $value<br>";
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template