To add an item to a Set in PHP, you can use the add
method of the SplObjectStorage class.
In this example,
mySet
.attach
method to add an item to mySet
.<?php
$mySet = new SplObjectStorage();
$object = new stdClass();
$object->name = "John Doe";
$mySet->attach($object);
var_dump($mySet);
?>
object(SplObjectStorage)#1 (1) { ["$storage":"SplObjectStorage":private]=> array(1) { [0]=> object(stdClass)#2 (1) { ["name"]=> string(8) "John Doe" } } }
In this example,
numberSet
.attach
method to add an integer to numberSet
.<?php
$numberSet = new SplObjectStorage();
$number = 123;
$numberSet->attach($number);
var_dump($numberSet);
?>
object(SplObjectStorage)#1 (1) { ["$storage":"SplObjectStorage":private]=> array(1) { [0]=> int(123) } }
In this tutorial, we learned How to add an Item to a Set in PHP language with well detailed examples.