Are there any data structures in php
other than array
. Is it possible to create a data structure such as an ArrayList
? If so please provide some references or some kind of implementation.
The closest PHP likeness to the ArrayList class from Java is the ArrayObject class. The method names are different, but the functionality between the two is fairly close. but it doesn't have contains method.
The list function in PHP is an inbuilt function which is used to assign the array values to multiple variables at a time while execution. Like array (), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.
Create an Array in PHP In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.
The list() function is used to assign values to a list of variables in one operation. Note: Prior to PHP 7.1, this function only worked on numerical arrays.
Everything you need to know about arrays can be found in the documentation.
All of the available functions for arrays are listed in the functions reference.
Some notes:
In the following I tried to list the PHP alternatives for the most common ArrayList
methods:
add(element)
is basically just appending via $array[] = $element
. The new value gets the next free numeric index (this is the preferred way). You can also use array_push($array, $element)
.addAll(ArrayList)
: array_merge($array1, $array2)
in a way. Be careful when merging associative arrays. Values for the same keys will be overwritten.clone()
: As arrays are not objects, you "clone" an array by just assigning it to another variable:
$a = array(1,2,3); $b = $a;
contains(element)
: in_array($element, $array)
get(index)
: Like in most languages: $val = $array[index];
indexOf(element)
: array_keys($array, $element)
with the value you search for as second parameterisEmpty()
: empty($array)
remove(index)
: Its unset($array[index])
remove(value)
with value: You have to get the keys first (see indexOf
), iterate over they keys and use unset
.size()
: count($array)
I tried to implement, here's some simple code:
class ArrayList { private $list = array(); public function Add($obj) { array_push($this->list, $obj); } public function Remove($key) { if(array_key_exists($key, $this->list)) { unset($this->list[$key]); } } public function Size() { return count($this->list); } public function IsEmpty() { return empty($this->list); } public function GetObj($key) { if(array_key_exists($key, $this->list)) { return $this->list[$key]; } else { return NULL; } } public function GetKey($obj) { $arrKeys = array_keys($this->list, $obj); if(empty($arrKeys)) { return -1; } else { return $arrKeys[0]; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With