Home > Article > Backend Development > php how to get array in object
In PHP, an object is a complex data type. Its properties can be basic data types or complex data types, including arrays, etc.
It is common to access arrays in objects. Normally, we can access the value of an object property through the arrow symbol (->), for example:
$obj->arrayProperty[0];
The above code is accessed The first element of an array named arrayProperty in the $obj object.
However, sometimes, we need to further operate the elements in the array, and at this time we need to use PHP's array function for processing. Below we will introduce some commonly used array functions in PHP to implement operations on arrays in objects.
array_values() function returns a new array containing only the array values in the object, and the key names of the new array will be incrementing numbers. Reindex. For example:
<?php class myClass { public $arrayProperty = array('foo', 'bar', 'baz'); } $obj = new myClass(); $array = array_values($obj->arrayProperty); print_r($array); ?>
Output:
Array ( [0] => foo [1] => bar [2] => baz )
Use the foreach loop to traverse the array in the object. For example:
<?php class myClass { public $arrayProperty = array('foo', 'bar', 'baz'); } $obj = new myClass(); foreach ($obj->arrayProperty as $value) { echo $value . ','; } ?>
Output:
foo,bar,baz,
array_map() function can apply a callback function to each element of the array , returns a new array containing the result returned after each element is acted upon by the callback function. For example:
<?php class myClass { public $arrayProperty = array('foo', 'bar', 'baz'); } $obj = new myClass(); $newArray = array_map(function($value){ return strtoupper($value); }, $obj->arrayProperty); print_r($newArray); ?>
Output:
Array ( [0] => foo [1] => bar [2] => baz )
array_filter() function can filter the elements in the array and return a filtered new An array containing only elements for which the callback function returns true. For example:
<?php class myClass { public $arrayProperty = array('foo', 'bar', 'baz'); } $obj = new myClass(); $newArray = array_filter($obj->arrayProperty, function($value){ return $value != 'bar'; }); print_r($newArray); ?>
Output:
Array ( [0] => foo [2] => baz )
The above are some of the commonly used array functions in PHP to access arrays in objects. These functions can help us operate arrays in objects more conveniently.
The above is the detailed content of php how to get array in object. For more information, please follow other related articles on the PHP Chinese website!