To create an empty set in PHP, you can use the SplObjectStorage
class, which is the closest equivalent to a set data structure in PHP.
In this example,
SplObjectStorage
class which is a built-in class in PHP that allows you to create a collection of objects, behaving similarly to a set.SplObjectStorage
class by calling its constructor with no arguments.$set1
and assign it the result of calling the new SplObjectStorage()
constructor.new SplObjectStorage()
constructor creates a new, empty set-like storage.$set1
using the var_dump
function to verify its contents.<?php
$set1 = new SplObjectStorage();
var_dump($set1);
?>
object(SplObjectStorage)#1 (0) { }
In this example,
SplObjectStorage
class to serve as our set by calling the new SplObjectStorage()
constructor.$set2
and assign it the result of the new SplObjectStorage()
constructor.stdClass
and assign properties to them.$set2
using the attach
method of the SplObjectStorage
class.$set2
using the var_dump
function to verify its contents.<?php
$set2 = new SplObjectStorage();
$object1 = new stdClass();
$object1->name = 'apple';
$set2->attach($object1);
$object2 = new stdClass();
$object2->name = 'banana';
$set2->attach($object2);
var_dump($set2);
?>
object(SplObjectStorage)#1 (2) { [0]=> object(stdClass)#2 (1) { ["name"]=> string(5) "apple" } [1]=> object(stdClass)#3 (1) { ["name"]=> string(6) "banana" } }
In this tutorial, we learned How to create an Empty Set in PHP language with well detailed examples.