To initialize a set in PHP, you can use an associative array or the SplObjectStorage
class.
In this example,
$set1
and assign it an empty array []
.$set1
using the var_dump
function to verify its contents.<?php
$set1 = [];
var_dump($set1);
?>
array(0) { }
In this example,
$set2
and assign it an array containing elements, such as 'apple'
, 'banana'
, and 'cherry'
.$set2
using the var_dump
function to verify its contents.<?php
$set2 = ['apple', 'banana', 'cherry'];
var_dump($set2);
?>
array(3) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(6) "cherry" }
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.$set3
and assign it the result of calling the new SplObjectStorage()
constructor.new SplObjectStorage()
constructor creates an empty set-like storage.$set3
using the var_dump
function to verify its contents.<?php
$set3 = new SplObjectStorage();
var_dump($set3);
?>
object(SplObjectStorage)#1 (0) { }
In this tutorial, we learned How to Initialize a Set in PHP language with well detailed examples.