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

What is the difference between arrays and objects in PHP?

WBOY
WBOYOriginal
2024-04-29 14:39:01783browse

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'];

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

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

Loop through the array

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

Loop through the object properties

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!

Statement:
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