How to create and manipulate lists in PHP?

Asked

Viewed 6,664 times

14

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

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

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


My doubt

I wonder if in PHP there is a feature similar to Java for handling and creating lists?

  • 3

    Well in PHP you can manipulate a list, more or less like this there, but you won’t be able to restrict the types of data that the list will receive.

  • 2
  • 2

    I agree with almost everything you are saying, but I can create an enumeration without if with type passed in the methods (already it happened this in previous version of PHP and now strongly in version 7) with return also of a certain type. Of course it’s not Generics equal C# or Java, but, I can create the particular enumeration, which in my view depending on the case does not need, imagine creating an enumeration for each classe would be bad for development.

2 answers

15


PHP is not a language with much type discipline.

In PHP there is a resource called array. The 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";

Upshot:

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

In that case, the order of array does not depend on the numbering/naming an index receives, but on the order it displays.

Then this below would work:

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


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

Splfixedarray - an SPL resource

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

Behold:

 $arr = new SplFixedArray(3);

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

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

You can make 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’s an example I put together 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 thus be:

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

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

See it working on Ideone.

Note: The class created above is just one example. It is up to each one how to implement some resource, but I do not think it is feasible to do as exemplified, since PHP is a language weakly tipada (Don’t go out with a master of OOP ;) ).

You still want to go further with this?

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

Behold:

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


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

If you added one string (not numerical), would return an error:

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

Error returned:

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

Other resources available in the SPL

In addition to being able to implement, PHP also offers some new features, such as the class called SplObjectStorage, which has the purpose of working with object storage.

In addition to the above, we also have:

  • Spldoublylinkedlist
  • Splstack
  • Splqueue
  • Splheap
  • Splmaxheap
  • Splminheap
  • Splpriorityqueue
  • Splfixedarray
  • Splobjectstorage

Besides this little list there, maybe it is important to quote about the Generators.

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

Read more:

  • 4

    He said SPL, he died to me :D

  • 2

    @bigown agree in part, I personally do not use, but spl_autoload is almost fundamental XD PS: +1

9

Is the array even normal. The array PHP is not a array as we know in other languages. They are lists by definition.

Remember that PHP is a language of script, it is not made 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 the structures allow you to put anything. So if you want to know if there’s any way to narrow down the list strings. You can’t. You’d have to have algorithms to ensure that.

Of course you can create a class to abstract this treatment if you want. Everything will be solved at runtime (in PHP it is always so), IE, will have a if when adding the element that will check if it is string to allow inclusion or not. Implementations will normally be naive and will perform HashMap and not of Array, as in lists in Java. But in PHP nobody cares for performance.

Example:

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

Some people prefer to aray_push():

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Note that the array PHP can take an associative form, that is, can behave like the HashMap, ie is a key and value pair. You don’t have much control over it. Just put an element that runs away from a sequence and is already a map.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.