Korr Iamnot
Korr Iamnot

Reputation: 309

searching for PHP equivalent for Java's Map and List?

In Java case#1:

Map m1 = new LinkedHashMap();
List l1 = new LinkedList();
m1.put("key1","val1");
m1.put("key2","val2");
l1.add(m1);

In java case#2

List l1 = new LinkedList();
l1.add("val1");
l1.add("val2");
l1.add("val3");

What's about in PHP for these cases ?

Upvotes: 1

Views: 3201

Answers (3)

Jon
Jon

Reputation: 437904

In PHP, arrays serve as all types of containers. They can be used as maps, lists and sets.

Linked list functionality is provided through the reset/prev/current/next/end functions; have a look at the "see also" section of the docs to make sure you don't miss any of them.

For map functionality you just index into the array directly; but keep in mind that array keys in PHP can only be strings or integers, and also that most of the time mixing both in the same array is not the right thing to do (although there is no technical reason not to, and there are cases where it makes sense).

SPL provides the SplDoublyLinkedList class, but there's nothing in there that a simple array doesn't also give you.

Upvotes: 2

Aleks G
Aleks G

Reputation: 57346

Normally you would use arrays for both cases:

In PHP case#1:

$m1 = array();
$l1 = array();
$m1['key1'] = 'val1';
$m1['key2'] = 'val2';
$l1[] = $m1;

In PHP case#2

$l1 = array();
$l1[] = "val1";
$l1[] = "val2";
$l1[] = "val3";

Then, to go through elements of the list, you can use foreach or reset/prev/current/next/end set of functions.

If using PHP5, you can also look at SPL data structures.

Upvotes: 1

adrien
adrien

Reputation: 4439

Even if array is the most used type in PHP, you should have a look to the SPL if using PHP 5.

With the SPL you got:

  • stack
  • queue
  • linked list
  • and so on...

Manual

Upvotes: 0

Related Questions