-1

I probably am asking this(1. as a newbie & 2. as a result of my own curiosity in what really happens). And my question is based on if data is pulled from DB, which is the recommended way and why? I have seen code from other developers that access elements of an array using the first scenario but I haven't seen the json_encode or json_decode

$x = array("fname" => "John", "lname" => "Doe", "age" => 28);

first scenario, to access an element say fname

$x = json_encode($x); // a
$x = json_decode($x); // b
echo $x->fname; // (c) outputs John

Scenario 2

// comment a, b and c above
// to access the same element fname
echo $x['fname']; // outputs John
BekiTheMe
  • 21
  • 8
  • If you have an array, you should use it as an array. Encode and decode only to have an object is a waste of time and resources. About your initial question, at the end of the first scenario you have an [StdClass](http://krisjordan.com/dynamic-properties-in-php-with-stdclass). StdClass is great when using Soap or when communicating with some other technologies, but is not designed to be used everywhere, please see [this answer](https://stackoverflow.com/a/3193790/4932315) that explains it. – Anthony May 26 '18 at 13:45
  • @AnthonyB thats very helpful! I got insights in why arrays are better as compared to `StdClass`. I have also noted that a `StdClass` will not do me any good interms of and when am required to use say array functions and I totally agree with that. I have also learnt the cases where to use each of them. Thanks, this is the answer I was looking for. – BekiTheMe May 27 '18 at 13:45
  • Possible duplicate of [When should I use stdClass and when should I use an array in php oo code?](https://stackoverflow.com/questions/3193765/when-should-i-use-stdclass-and-when-should-i-use-an-array-in-php-oo-code) – Anthony May 27 '18 at 16:11

2 Answers2

1

By default the json_decode() function returns an object. You can optionally specify a second parameter, which accepts a boolean value that when set as true JSON objects are decoded into associative arrays. It is false by default.

$x = array("fname" => "John", "lname"=> "Doe", "age" => 28);

$x = json_encode($x);
$x = json_decode($x, true);
echo $x->fname;
echo $x["fname"];
0

All things are in the dev's programing style. The first scenario shows the code more pretty (OOP style) In the second, simple and does not look like code from "a professional dev"

but both are strictly the same

Huntr
  • 59
  • 1
  • 5
  • I would upvoted because it's indeed about dev style, but it would be better with some exampls, explanations, references to external articles or documentation. – Anthony May 26 '18 at 13:58