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.
6 Answers
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:
- Arrays were originally the only datastructure in PHP. That is why they are so flexible. They were meant to be used as stack, queue, array, list, hash table and so forth. Later on PHP introduced the spl Datastructures.
- Unlike Java, PHP is not a pure OO language. An array itself has no built in methods you can apply. This has to be done via "normal" functions.
- Arrays have no fixed size. They expand and shrink automatically.
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 usearray_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)
: Itsunset($array[index])
remove(value)
with value: You have to get the keys first (seeindexOf
), iterate over they keys and useunset
.size()
:count($array)
-
2umm, the only datastructure? what about php.net/manual/en/spl.datastructures.php– GordonCommented Feb 14, 2012 at 22:24
-
1Point taken. I was more thinking about built-in datastructures... but to be honest I don't know how popular the ones are you linked to. I have never used them which does not have to mean anything. Commented Feb 15, 2012 at 0:03
-
Hey @Cooper, mark this answer as correct! This explains everything there is to know about arrays in PHP. It helped me too.– BorisCommented May 5, 2012 at 10:37
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];
}
}
}
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.
ArrayObject implements IteratorAggregate , ArrayAccess , Serializable , Countable {
/* Constants */
const integer STD_PROP_LIST = 1 ;
const integer ARRAY_AS_PROPS = 2 ;
/* Methods */
public __construct ([ mixed $input = [] [, int $flags = 0 [, string $iterator_class = "ArrayIterator" ]]] )
public void append ( mixed $value )
public void asort ( void )
public int count ( void )
public array exchangeArray ( mixed $input )
public array getArrayCopy ( void )
public int getFlags ( void )
public ArrayIterator getIterator ( void )
public string getIteratorClass ( void )
public void ksort ( void )
public void natcasesort ( void )
public void natsort ( void )
public bool offsetExists ( mixed $index )
public mixed offsetGet ( mixed $index )
public void offsetSet ( mixed $index , mixed $newval )
public void offsetUnset ( mixed $index )
public string serialize ( void )
public void setFlags ( int $flags )
public void setIteratorClass ( string $iterator_class )
public void uasort ( callable $cmp_function )
public void uksort ( callable $cmp_function )
public void unserialize ( string $serialized )
}
-
1
array(
'key' => 'value',
'key2' => 'value2'
)
or
class DataStructure {
var $val1;
var $val2;
}
$item = new DataStructure();
$item -> val1 = 'value1';
I have no idea what this "arrayList" is (sounds Java), but if it's a list of arrays, the PHP equivalent would be :
array(
array(
'item1',
'item2'
),
array(
'item1',
'item2'
)
)
[edit]
If this arrayList
is simply an array, you could use
array(
'item1',
'item2'
)
-
array list actully is an array but with enhanced features. such as there exist predefinde method that help to add a new element in the array even you exceed the array size .for example if an array a with size 5 and you want to add the element number 6 you shouldn't care about the process of rewriting the all elements in a new array with size 5+1 to add your last element .also sorting ..etc– CooperCommented Dec 31, 2010 at 13:14
If you (or anyone else reading this) simply wants (for whatever reason) a Java like ArrayList for PHP, you can use this.
Full Source: http://www.phpclasses.org/browse/file/4191.html
/**
* ArrayList class
* @version 0.2
* @author Tim Anlauf <[email protected]>
* @url http://www.phpclasses.org/browse/file/4191.html
**/
class ArrayList {
function ArrayList($arr="")
function addToPos($index, $obj)
function add($obj)
function addAll($arr)
function clear()
function contains($obj)
function get($index)
function indexOf($obj)
function isEmpty()
function lastIndexOf($obj)
function remove($index)
function removeRange($fromIndex, $toIndex)
function size()
function sort()
function toArray()
function hasNext()
function reset()
function next()
function isInteger($toCheck)
}
by extending the ArrayObject class, you might be able to create some basic class really easily (such as Vector, Collection of ArrayList).
ArrayList
.ArrayList
in Java are, for the most part, either built into PHP arrays or available via global functions (e.g.,sort
). See, for instance, php.net/manual/en/language.types.array.php . That link was the second hit on a Google search for: php array list. You could've easily located it yourself.