Data
Map
PHP
$arr = ['name'=>'Sam', 'age'=>25];
$stdclass = new StdClass;
$splobj = new SplObjectStorage();
There are couple of tools in PHP for having Map interface:
- Associative Array
- StdClass
- SplObjectStorage
$arr = [
'name' => 'Sam',
'age' => 25
];
Arrays in PHP can have key/value structure.
This kind of Array is called Associative Array.
$arr = ['name'=>'Sam', 'age'=>25];
$val = $arr['name']; // 'Sam'
You can access a value in associative array using the bracket operator.
$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.
$arr = ['name'=>'Sam', 'age'=>25];
$length = count($arr); // 2
The count()
function returns the number of elements in an array.
$arr = ['name'=>'Sam', 'age'=>25];
unset($arr['age']); // $arr -> ['name'=>'Sam']
The unset()
function deletes a key (and its value) in an associative Array.
$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.
$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.
$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.
$obj = new stdClass();
$obj->name = 'Sam';
$obj->age = 25;
$name = $obj->name; // 'Sam'
You can access any property defined on stdClass object using ->
operator.
$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.
$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.
$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.
$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.