Posts Learn Components Snippets Categories Tags Tools About
/

How to Access stdClass Property that has Spaces in PHP

Learn how to access the stdClass/class property with spaces in PHP. Learn this trick and be able to access any json decoded value.

Created on Sep 18, 2021

3196 views

In this short snippet, you will learn how to accessing stdClass/Class properties with spaces in PHP. This scenario typically arise when you are using a JSON decode method in PHP which will then return a stdClass object. For this example do imagine that you have stdClass like below.
{#1293
     +"First Name": "John",
     +"Last Name": "Doe",
     +"Address": "Street 123"
}
Generally, if there are no spaces then you could just make use of the normal way "$object->property" but if there is space like the "First Name" and "Last Name" like above, then you can make use of the curly brackets.
"{}".
<?php

$property = 'First Name';
$object->{$property};
Or you can simply write it into a one-liner.
$object->{'First Name'};
If you want to check using the null coalescing operator then you can write it like below.
$object?->{'First Name'};
By now you should be able to get the value of the class properties that has a space in PHP. if you find this tutorial helpful do share it with your friends and cheers!

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)