How to create and manipulate lists in PHP?

9

In java it is possible to create and manipulate list of any data type using List<E> , see the example below:

List<String> lista = new ArrayList<>();
lista.add("Stack");
lista.add("Over");
lista.add("flow");

I created a list of type String and added three values to it using the add() method.

My question

I would like to know if there is any Java-like feature for manipulating and creating lists in PHP?

    
asked by anonymous 06.10.2016 / 15:21

2 answers

11

PHP is not a language with a lot of type discipline.

In PHP there is a resource called array . array can be a numbered or indexed list - and can also be both at the same time.

For example:

 $arr = [];

 $arr[] = "Stack";
 $arr[] = "Over";
 $arr[] = "Flow";

Result:

[
  "Stack",
  "Over",
  "Flow",
]

In this case, the order of array does not depend on the numbering / naming that an index receives, but on the order they are displayed.

So this would work fine:

 $arr[98] = "Stack";
 $arr['96'] = "Over";
 $arr[97] = "Flow";


[
  98 => "Stack",
  96 => "Over",
  97 => "Flow",
]

SplFixedArray - an SPL feature

In my opinion, the PHP mechanism closest to presenting in the question is the SplFixedArray class. This class is part of the standard PHP library, called SPL . With this class, you can determine an object with a list with a limited number of elements.

See:

 $arr = new SplFixedArray(3);

 $arr[] = 1;
 $arr[] = 2;
 $arr[] = 3;
 $arr[] = 4; // Lança uma exceção, pois o número é limitado.

But back to the beginning of this answer, the resource you need would be array itself. The SplFixedArray guarantees the limit of elements that will be added, but has no type restriction.

You can do an implementation

In PHP there are two special interfaces called ArrayAccess and Iterator . With these two, you can create a class by determining the type of elements that can be added to your list.

Here is an example I put up for you:

class StringList implements ArrayAccess, IteratorAggregate
{
    protected $items = [];

    public function offsetSet($key, $value)
    {
        if (is_string($value)) {

            $key ? $this->items[$key] = $value : array_push($this->items, $value);

            return $this;
        }

        throw new \UnexpectedValueException('Essa é uma lista que aceita somente string');
    }

    public function offsetGet($key)
    {
        return $this->items[$key];
    }

    public function offsetExists($key)
    {
        return isset($this->items[$key]);
    }

    public function offsetUnset($key)
    {
        unset($this->items[$key]);
    }

    public function getIterator()
    {
        return new ArrayIterator($this->items);
    }
}

The use of the class would look like this:

$list = new StringList;
$list[] = 'Wallace';
$list[] = 'Bigown';
$list[] = 'Denner Carvalho';
$list[] = 1; // Se fizer isso vai lancar exceção

foreach ($list as $string) {
    var_dump($string);
}

See this working on Ideone .

Note : The class created above is just an example. It is at the discretion of each one how to implement some feature, however I do not think it is feasible to do as exemplified, since PHP is a weakly typed language (nothing to come out giving a master of OOP ) ).

Still want to go further with this?

In PHP 7, there is a feature that lets you set the argument type of a function. Combining this with the ellipsis operator, you can do a "hack" to create a array (list style) with specific types.

See:

function int_list(int ...$strings)
{
    return $strings;
}


int_list(1, 2, 3, 4, 5);

If you add a% (not a numeric)%, it would return an error:

int_list(1, 2, 3, 4, 5, 'x');

Error returned:

  

Argument 6 passed to int_list () must be of type integer, string given

Other features available in SPL

In addition to being able to implement, PHP also offers some new features, such as the class called SplObjectStorage , which is intended to work with object storage.

In addition to the above, we also have:

  • SplDoublyLinkedList
  • SplStack
  • SplQueue
  • SplHeap
  • SplMaxHeap
  • SplMinHeap
  • SplPriorityQueue
  • SplFixedArray
  • SplObjectStorage

In addition to this list, it may be important to quote about the Generators .

Of course, these features will never compare to a typed language, as in the case of Java or C #.

Read more:

06.10.2016 / 15:25
6

It is the same array . The array of PHP is not a real array , as we know it in other languages. They are lists by definition.

Remember that PHP is a script language, it was not meant to have the best robustness and performance in the application of data structures. However this gives great flexibility and ease of use. Java prefers the specialization path to get the best result.

PHP is a dynamically typed language, and structures allow you to place anything. So you wonder if you can restrict the list to just strings . It does not. It would have to have algorithms to ensure that.

Of course you can create a class to abstract this treatment if you want. Everything will be resolved at runtime (in PHP it is always anyway), that is, it will have a if when adding the element that will check if it is string to allow inclusion or not. The implementations will usually be naive and will have performance of HashMap and not of Array , as it happens in lists in Java. But in PHP nobody cares about performance.

Example:

$lista = [];
$lista[] = "Stack";
$lista[] = "Over";
$lista[] = "flow";

Some people prefer it with aray_push() :

$lista = array();
array_push($lista, "Stack");
array_push($lista, "Over");
array_push($lista, "flow");

See working on ideone or in PHP Sandobox .

Note that the array of PHP can assume an associative form , that is, it can behave like HashMap , that is, it is a key and value pair. You do not have much control over it. Just place an element that runs away from a sequence and is already a map.

    
06.10.2016 / 15:28