Data

Map

PHP

 

Defining Map

PHP 5
$arr = ['name'=>'Sam', 'age'=>25];

$stdclass = new StdClass;

$splobj = new SplObjectStorage();

There are couple of tools in PHP for having Map interface:

 

Defining Associative Array

PHP 5
$arr = [ 
  'name' => 'Sam', 
  'age' => 25 
];

Arrays in PHP can have key/value structure.

This kind of Array is called Associative Array.

 

Getting Key

PHP 5
$arr = ['name'=>'Sam', 'age'=>25];

$val = $arr['name'];  // 'Sam'

You can access a value in associative array using the bracket operator.

 

Setting Key/Value

PHP 5
$arr = ['name'=>'Sam', 'age'=>25];

$arr['age'] = 21;

You can set a key or update an existing key with a new value using the bracket operator.

Here we are setting a value for key age to 21.

 

Length

PHP 5
$arr = ['name'=>'Sam', 'age'=>25];

$length = count($arr);  // 2

The count() function returns the number of elements in an array.

 

Deleting Key

PHP 5
$arr = ['name'=>'Sam', 'age'=>25];

unset($arr['age']);  // $arr -> ['name'=>'Sam']

The unset() function deletes a key (and its value) in an associative Array.

 

Listing Keys

PHP 5
$arr = ['name'=>'Sam', 'age'=>25];

$keys = array_keys($arr); // ['name','age']

The array_keys() function returns an indexed array of all keys in an associative array.

 

Listing Values

PHP 5
$arr = ['name'=>'Sam', 'age'=>25];

$values = array_values($arr); // ['Sam',25]

The array_values() function returns an indexed array of all values in an associative array.

 

Defining stdClass

PHP 5
$obj = new stdClass();

$obj->name = 'Sam';
$obj->age = 25;

stdClass is a generic empty class in PHP.

It can be used to store key/value pairs.

 

Getting Key

PHP 5
$obj = new stdClass();

$obj->name = 'Sam';
$obj->age = 25;

$name = $obj->name;  // 'Sam'

You can access any property defined on stdClass object using -> operator.

 

Setting Key/Value

PHP 5
$obj = new stdClass();

$obj->name = 'Sam';
$obj->age = 25;

You can set a property or update an existing property with a new value using -> operator.

Here we are setting a value for property name to Sam and age to 25.

 

Length

PHP 5
$obj = new stdClass();

$obj->name = 'Sam';
$obj->age = 25;

$count = count((array)$obj);  // 2

You can cast an object to an array and use count() on it to get the number of properties set on that object.

 

Deleting Key

PHP 5
$obj = new stdClass();

$obj->name = 'Sam';
$obj->age = 25;

unset($obj->age);   // $obj -> ['name'=>'Sam']

The unset() function deletes a property (and its value) from an object.

 

Listing Keys

PHP 5
$obj = new stdClass();

$obj->name = 'Sam';
$obj->age = 25;

$keys = array_keys((array) $obj); // ['name','age']

You can cast an object to an array and use array_keys() on it to get the object properties.

 

Listing Values

PHP 5
$obj = new stdClass();

$obj->name = 'Sam';
$obj->age = 25;

$values = array_values((array) $obj); // ['Sam',25]

You can cast an object to an array and use array_values() on it to get the object properties.