Php construct an array

The ArrayObject class

Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).

ArrayObject::ARRAY_AS_PROPS

Entries can be accessed as properties (read and write).

Table of Contents

  • ArrayObject::append — Appends the value
  • ArrayObject::asort — Sort the entries by value
  • ArrayObject::__construct — Construct a new array object
  • ArrayObject::count — Get the number of public properties in the ArrayObject
  • ArrayObject::exchangeArray — Exchange the array for another one
  • ArrayObject::getArrayCopy — Creates a copy of the ArrayObject
  • ArrayObject::getFlags — Gets the behavior flags
  • ArrayObject::getIterator — Create a new iterator from an ArrayObject instance
  • ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject
  • ArrayObject::ksort — Sort the entries by key
  • ArrayObject::natcasesort — Sort an array using a case insensitive «natural order» algorithm
  • ArrayObject::natsort — Sort entries using a «natural order» algorithm
  • ArrayObject::offsetExists — Returns whether the requested index exists
  • ArrayObject::offsetGet — Returns the value at the specified index
  • ArrayObject::offsetSet — Sets the value at the specified index to newval
  • ArrayObject::offsetUnset — Unsets the value at the specified index
  • ArrayObject::serialize — Serialize an ArrayObject
  • ArrayObject::setFlags — Sets the behavior flags
  • ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject
  • ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function
  • ArrayObject::unserialize — Unserialize an ArrayObject

User Contributed Notes 22 notes

As you know ArrayObject is not an array so you can’t use the built in array functions. Here’s a trick around that:

Extend the ArrayObject class with your own and implement this magic method:

public function __call ( $func , $argv )
if (! is_callable ( $func ) || substr ( $func , 0 , 6 ) !== ‘array_’ )
throw new BadMethodCallException ( __CLASS__ . ‘->’ . $func );
>
return call_user_func_array ( $func , array_merge (array( $this -> getArrayCopy ()), $argv ));
>
?>

Now you can do this with any array_* function:
$yourObject -> array_keys ();
?>
— Don’t forget to ommit the first parameter — it’s automatic!

Note: You might want to write your own functions if you’re working with large sets of data.

There is a better explanation about the ArrayObject flags (STD_PROP_LIST and ARRAY_AS_PROPS) right here:

If you need the last key of your collection use:
array_key_last ( $this -> getArrayCopy ())
?>

In an extending class it could look like:
class Collection extends ArrayObject
public function lastKey (): int
return array_key_last ( $this -> getArrayCopy ());
>
>
?>

If you want to use any type safe collection:
class BookCollection extends Collection
public function add ( Book $book ) : void
$this -> offsetSet ( $book -> id , $book );
>

// note the return type «Book»
public function get ( int $bookId ) : Book
$this -> offsetGet ( $bookId );
>
>
?>

Generally variable $this can’t be used as an array within an object context. For example, following code piece would cause a fatal error:

Читайте также:  Стили

class TestThis public function __set ( $name , $val ) $this [ $name ] = $val ;
>

public function __get ( $name ) return $this [ $name ];
>
>

$obj = new TestThis ();
$obj -> a = ‘aaa’ ;
echo $obj -> a . «\n» ;
?>

But things are different when $this is used in an ArrayObject object. e.g., following code piece are valid:

class TestArrayObject extends ArrayObject <
public function __set ( $name , $val ) $this [ $name ] = $val ;
>

public function __get ( $name ) return $this [ $name ];
>
>

$obj = new TestArrayObject ();
$obj -> a = ‘aaa’ ;
echo $obj -> a . «\n» ;
?>

I found the description of STD_PROP_LIST a bit vague, so I put together a simple demonstration to show its behavior:

$a = new ArrayObject (array(), ArrayObject :: STD_PROP_LIST );
$a [ ‘arr’ ] = ‘array data’ ;
$a -> prop = ‘prop data’ ;
$b = new ArrayObject ();
$b [ ‘arr’ ] = ‘array data’ ;
$b -> prop = ‘prop data’ ;

// ArrayObject Object
// (
// [prop] => prop data
// )
print_r ( $a );

// ArrayObject Object
// (
// [arr] => array data
// )
print_r ( $b );

// Example STD_PROP_LIST and ARRAY_AS_PROP combined
$ao = new ArrayObject ();
$ao -> setFlags ( ArrayObject :: STD_PROP_LIST | ArrayObject :: ARRAY_AS_PROPS );

$ao -> prop = ‘prop data’ ;
$ao [ ‘arr’ ] = ‘array data’ ;

ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[prop] => prop data
[arr] => array data
)

I don’t believe the same performance is true since PHP 5.3. Using the same fill, read_key and foreach approach on both native arrays and ArrayObjects with 10000 keys I get the following

array() fill 0.013101
array() read 0.008685
array() foreach 0.004319
ArrayObject fill 0.014136
ArrayObject read 0.010003
ArrayObject foreach 3.454612

array() fill 0.010395
array() read 0.005933
array() foreach 0.001903
ArrayObject fill 0.010598
ArrayObject read 0.006387
ArrayObject foreach 0.003451

This was the code I used for both, an array or ArrayObject is passed into each of the functions. Again PEAR::Benchmark was used to get the results.

If you want to use built-in array function with ArrayObject, store the iterator instance and return the value as reference in offsetGet.

$this -> iterator = $this -> getIterator ();
parent :: __construct ( $data );
>

To implement array-style appending (e.g. «$object[] = ‘foo’;») in your own class implementing the ArrayAccess _interface_, all you need do is check if the key passed to your implementation of offsetSet() is NULL. Something like the following.

class MyArrayObject implements ArrayAccess

/**
* @see ArrayAccess::offsetSet()
*/
public function offsetSet ( $p_key , $p_value ) if ( is_null ( $p_key )) $this -> aValue [] = $p_value ;
>
else $this -> aValue [ $p_key ] = $p_value ;
>
>

If you plan to derive your own class from ArrayObject, and wish to maintain complete ArrayObject functionality (such as being able to cast to an array), it is necessary to use ArrayObject’s own private property «storage».

Since that is impossible to do directly, you must use ArrayObject’s offset methods to manipulate it indirectly.

As a side benefit, this means you inherit all the iteration and other functions in complete working order.

This may sound obvious to someone who has never implemented their own ArrayObject class. but it is far from so.

class MyArrayObject extends ArrayObject <
static $debugLevel = 2 ;

Читайте также:  Datetime format python django

static public function sdprintf () <
if (static:: $debugLevel > 1 ) <
call_user_func_array ( «printf» , func_get_args ());
>
>

public function offsetGet ( $name ) <
self :: sdprintf ( «%s(%s)\n» , __FUNCTION__ , implode ( «,» , func_get_args ()));
return call_user_func_array (array( parent , __FUNCTION__ ), func_get_args ());
>
public function offsetSet ( $name , $value ) <
self :: sdprintf ( «%s(%s)\n» , __FUNCTION__ , implode ( «,» , func_get_args ()));
return call_user_func_array (array( parent , __FUNCTION__ ), func_get_args ());
>
public function offsetExists ( $name ) <
self :: sdprintf ( «%s(%s)\n» , __FUNCTION__ , implode ( «,» , func_get_args ()));
return call_user_func_array (array( parent , __FUNCTION__ ), func_get_args ());
>
public function offsetUnset ( $name ) <
self :: sdprintf ( «%s(%s)\n» , __FUNCTION__ , implode ( «,» , func_get_args ()));
return call_user_func_array (array( parent , __FUNCTION__ ), func_get_args ());
>
>

$mao = new MyArrayObject ();
$mao [ «name» ] = «bob» ;
$mao [ «friend» ] = «jane» ;
print_r ((array) $mao );

offsetSet(name,bob)
offsetSet(friend,jane)
Array
(
[name] => bob
[friend] => jane
) */
?>

If you wish to use the «Array as Properties» flag, you simply need to include this in your constructor:

This will allow you to do things such as the below example, without overriding __get or __set .

$mao -> name = «Phil» ;
echo $mao [ «name» ]; /* Outputs «Phil» */
?>

Источник

PHP Array

Summary: in this tutorial, you’ll learn about PHP arrays and how to manipulate array elements effectively.

Introduction to PHP arrays

By definition, an array is a list of elements. So, for example, you may have an array that contains a list of products.

PHP provides you with two types of arrays: indexed and associative.

The keys of the indexed array are integers that start at 0. Typically, you use indexed arrays when you want to access the elements by their positions.

The keys of an associative array are strings. And you use associative arrays when you want to access elements by string keys.

This tutorial focuses on the indexed array.

Creating arrays

In PHP, you can use the array() construct or [] syntax to define an array. The [] syntax is shorter and more convenient.

1) Creating an array using array() construct

To define an array, you use the array() construct. The following example creates an empty array:

 $empty_array = array();Code language: HTML, XML (xml)

To create an array with some initial elements, you place a comma-separated list of elements within parentheses of the array() construct.

For example, the following defines an array that has three numbers:

 $scores = array(1, 2, 3);Code language: HTML, XML (xml)

2) Creating an array using the [] syntax

PHP provides a more convenient way to define arrays with the shorter syntax [], known as JSON notation. The following example uses [] syntax to create a new empty array:

 $empty_array = [];Code language: HTML, XML (xml)

The following example uses the [] syntax to create a new array that consists of three numbers:

 $scores = [1, 2, 3];Code language: HTML, XML (xml)

Displaying arrays

To show the contents of an array, you use the var_dump() function. For example:

 $scores = [1, 2, 3]; var_dump($scores);Code language: HTML, XML (xml)
array(3) < [0]=> int(1) [1]=> int(2) [2]=> int(3) >Code language: PHP (php)

Or you can use the print_r() function:

 $scores = array(1, 2, 3); print_r($scores);Code language: HTML, XML (xml)
Array ( [0] => 1 [1] => 2 [2] => 3 )Code language: PHP (php)

To make the output more readable, you can wrap the output of the print_r() function inside a tag. For example:

 $scores = [1, 2, 3]; echo '
'; print_r($scores); echo '

';Code language: HTML, XML (xml)

Array ( [0] => 1 [1] => 2 [2] => 3 )Code language: PHP (php)

It’s more convenient to define a function that prints out an array like this:

 function print_array($data) < echo '
'; print_r($data); echo '

'; > $scores = [1, 2, 3]; print_array($scores);Code language: HTML, XML (xml)

Array ( [0] => 1 [1] => 2 [2] => 3 )Code language: PHP (php)

And then you can reuse the function whenever you want to display an array.

Accessing array elements

To access an element in an array, you specify the index of the element within the square brackets:

$array_name[index]Code language: PHP (php)

Note that the index of the first element of an array begins with zero, not one.

The following example shows how to access the first element of the array:

 $scores = [1, 2, 3]; echo $scores[0];Code language: HTML, XML (xml)

Adding an element to the array

To add an element to an array, you use the following syntax:

$array_name[] = new_element;Code language: PHP (php)

PHP will calculate the highest numerical index plus one each time you assign an element to the array.

The following example shows how to add the number 4 to the $scores array:

 $scores = [1, 2, 3]; $scores[] = 4;Code language: HTML, XML (xml)

In this example, we defined an array that consists of three numbers initially. Then, we added the number 4 to the array.

It’s possible to use an index when you add a new element to the array. For example:

$scores = [1, 2, 3]; $scores[3] = 4;Code language: PHP (php)

But doing this, you have to calculate the new index manually. It is not practical. Also, if the index is already is used, the value will be overwritten.

Changing array elements

The following statement changes the element located at the index to the $new_element :

$array_name[index] = $new_element;Code language: PHP (php)

For example, to change the first element of the $scores array from 1 to zero, you do it as follows:

 $scores = [1, 2, 3]; $scores[0] = 0;Code language: HTML, XML (xml)

Removing array elements

To remove an element from an array, you use the unset() function. The following removes the second element of the $scores array:

 $scores = [1, 2, 3]; unset($scores[1]);Code language: HTML, XML (xml)

Getting the size of an array

To get the number of elements in an array, you use the count() function. For example:

 $scores = [1, 2, 3, 4, 5]; echo count($scores);Code language: HTML, XML (xml)

Summary

  • Use the array() construct or [] syntax to create a new array.
  • For the indexed array, the first index begins with zero.
  • To access an array element, use an index in the square bracket $array_name[index] .
  • Use the count() function to get the number of elements in an array.

Источник

Оцените статью