Does PHP allow to have duplicate properties inside an stdObject? - php

I'm stuck with a very weird bug. I have an object called $row that looks like this:
stdClass Object
(
[title] => Some Title
[body] => My body
[topic] => Topic
[dataType] => Survey
[csvrownum] => 1
)
I'm just trying to print out the title property in the following way:
print_r($row->title);
However for some reason that doesn't output anything.
Then I've tried to manually set the title property and print it right after, something like this:
$row->title = 'My Title';
print_r($row->title);
Surprisingly it worked but why? To make this more strange I decided to var_dump the object after set the title variable by hand:
$row->title = 'My Title';
var_dump($row);
And this is what I've got:
class stdClass#391 (6) {
public $title =>
string(3) "Some title"
public $body =>
string(7) "My body"
public $topic =>
string(6) "Topic"
public $dataType =>
string(17) "Survey"
public $csvrownum =>
int(1)
public $title =>
string(8) "My title"
}
Notice the title key is duplicated with different values. Is there any condition under this could happen?

No, PHP does not allow an object to have duplicate property names, because objects in PHP are implemented just like arrays. They are both implemented as ordered hashmaps. In a hashmap, two things that have the same hash, overwrite each other.
You likely just have unprintible characters in your object property name. You can see this more clearly by doing something like the following for debug purposes...
foreach($row as $key => $value) {
var_dump($key);
}
If we had an object like this, for example, you'd see it gets overwritten.
$row = new stdClass;
$row->title = "First";
$row->title = "Second";
But something like this might be more deceptive...
$row = new stdClass;
$row->{"title\0"} = "First";
$row->title = "Second";
Output from the foreach using var_dump on the key, would reveal this...
string(6) "title"
string(5) "title"
Notice one is string of length 6 and the other is a string of length 5.
Grain of salt
It's always better to use var_dump when attempting to debug variables than using something like print_r, as var_dump was specifically designed for debug purposes, whereas print_r is just a recursive print (hence the name). Printing values like null, false, or empty strings, gives you no useful information for debug purposes, but var_dump does.

Related

PHP array cannot get value from key

I got an object that has some private properties that i cannot access.
var_dump($roomType);
// I deleted some of the results of var_dump
object(MPHB\Entities\RoomType)#2003 (6) {
["id":"MPHB\Entities\RoomType":private]=> int(15)
["originalId":"MPHB\Entities\RoomType":private]=> int(15)
["description":"MPHB\Entities\RoomType":private]=> string(0) ""
["excerpt":"MPHB\Entities\RoomType":private]=> string(0) ""
["imageId":"MPHB\Entities\RoomType":private]=> int(406)
["status":"MPHB\Entities\RoomType":private]=> string(7) "publish" }
So I convert the object to array.
$array = (array) $roomType;
print_r($array);
/*
Array (
[MPHB\Entities\RoomTypeid] => 15
[MPHB\Entities\RoomTypeoriginalId] => 15
[MPHB\Entities\RoomTypedescription] =>
[MPHB\Entities\RoomTypeexcerpt] =>
[MPHB\Entities\RoomTypeimageId] => 406
[MPHB\Entities\RoomTypestatus] => publish )
*/
but I still cannot access the values from key like this
var_dump($array["MPHB\Entities\RoomTypeimageId"]); // NULL
The only workaround i got is this :
$array = (array) $roomType;
$array_keys = array_keys($array);
$array_key_id = $array_keys[4];
echo $array[$array_key_id]; // 406
But I am not sure that the key is at the same position all the time, so I want to find an other way.
I escaped the slashes but still the same, any ideas?
Edit :
So I tried to compare the $array_key_id (which is MPHB\Entities\RoomTypeimageId) with the same value (copied from the browser) and it fails.
So I did a loop and pushed the key=>value to the existing $array and now I can get the value.
There must be something like null bytes as BacLuc said.
I would guess that escaping is the problem:
$array["MPHB\Entities\RoomTypeimageId"] -> $array["MPHBEntitiesRoomTypeimageId"] for which there is no value in the array.
But $array["MPHB\\Entities\\RoomTypeimageId"] might work.
Edit:
it's escaping plus on private properties have the class name prepended to the property name, surrounded with null bytes.
Test is here: http://sandbox.onlinephpfunctions.com/code/d218d41f22e86dd861f562de9c040febb011d577
From:
Convert a PHP object to an associative array
https://www.php.net/manual/en/language.types.array.php#language.types.array.casting

PHP Array to Object

Given the following array:
$array = array(
'item_1' => array(
'item_1_1' => array(
'item_1_1_1' => 'Hello',
),
'item_1_2' => 'World',
),
'item_2' => array(),
);
How can I convert that into an Object?
Option 1
$obj = (object) $array;
Or
Option 2
$object = json_decode(json_encode($array), FALSE);
Or something else?
I would like to know the difference in the output between the 2 option and understand the best practice for creating this conversion.
Well you are answering somehow your own question, but if you want to have an object with the attributes like your array you have to cast it, this way an array will remain an array
$obj = (object) $array;
OUTPUT:
object(stdClass)#1 (2) {
["item_1"]=>
array(2) {
["item_1_1"]=>
array(1) {
["item_1_1_1"]=>
string(5) "Hello"
}
["item_1_2"]=>
string(5) "World"
}
["item_2"]=>
array(0) {
}
}
if you are using the json_decode version it will convert arrays to objects too:
object(stdClass)#2 (2) {
["item_1"]=>
object(stdClass)#3 (2) {
["item_1_1"]=>
object(stdClass)#4 (1) {
["item_1_1_1"]=>
string(5) "Hello"
}
["item_1_2"]=>
string(5) "World"
}
["item_2"]=>
array(0) {
}
}
NOTE: just the empty array will be an array here.
To Answer your question: The best practice depends on what YOU need.
It depends, really: if you are working on data that might be an array in one case, and an object the next, it would probably be best to use the json_decode trick, simply because unlike a cast, its result is "recursive". There is one very important thing to keep in mind here, though: numeric indexes can, and probably will cause problems for you at some point in time. Take a look at this bug report
This is documented here, but not in a way that really stands out:
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible;
Exampe of the problem:
$data = [
'foo' => 'bar',
123 => 'all is well',
];
$obj = json_decode(json_encode($data));
var_dump($obj->foo);//bar
var_dump($obj->{123});//all is well
$cast = (array) $obj;
var_dump($cast);//shows both keys
var_dump(isset($cast[123]));//FALSE!!!
var_dump(isset($cast['123']));//FALSE
Basically: If you start converting arrays to objects and back again, numeric keys are not reliable anymore. If I were you, I'd simply change the code that is passing the data where possible, or I'd create a value object that can be set using an array or an object, and normalize the data that way.

return passed array keys and values

I am working in WordPress. I am using a plugin to get the admin options. The plugin takes an argument as an ID to get the value from the database like so.
$option = ot_get_option('email_address');
The above line of code would return
myEmail#example.com
I want to write a helper function that would get multiple values at once. Normally, I would get the options like this.
$option_1 = ot_get_option('option1');
$option_2 = ot_get_option('option2');
$option_3 = ot_get_option('option3');
I figured there could be a better way that would look a little nicer. I put together this little function that does work
function ritual_get_options($arg_list = array())
{
$options = array();
foreach( $arg_list as $key => $value){
$options[] = ot_get_option($value, array());
}
return $options;
}
using the function above, I can now pass the id's of the options like so
ritual_get_options('option1','option2','option3');
My issue is that the above will return an array with numeric keys. 0,1,2. Here is the exact array that is getting returned when I do a var_dump on the front end
[0]=>
string(16) "100 Main Street,"
[1]=>
string(18) "Hamilton, Ontario."
[2]=>
string(15) "+1 800 999 9898"
[3]=>
string(19) "mail#yourdomain.com"
I want to return the array keys with the value so that I can easily figure out what value is in what key. Here is the line that I used to get the above array
$options = ritual_get_options(array('number' => 'streetnumber','street' => 'street','phone' => 'phone_number','email' => 'email'));
When I go to use the returned values, I want to be able to use the key so that I could do
echo $options['number'];
instead of doing
echo $options[0];
I have not been able to figure out how to return the keys passed in to the function and preserve them into through the return.
Set the option name as key while building the array:
foreach( $arg_list as $option ){
$options[$option] = ot_get_option( $option );
}
Btw, using extract() on the $options array will allow you to use e.g. $phone_number instead of $options['phone_number']

Adding variable for the context on a view, on Laravel 4

Lets say that I have a View that uses 3 variables, while developing on Laravel 4:
<ul>
<li>Name: {{name}}</li>
<li>Surname: {{surname}}</li>
<li>Age: {{age}}</li>
<ul>
In my controller, I could be adding the data to the view the following way.
$context = array('name' => $name, 'surname' => $surname, 'age' => $age);
return View::make('myview');
But this code isnt completely DRY, since I am writing twice the name of the variable. It would be optimal if I could do:
$context = array($name, $surname, $age);
return View::make('myview', $context);
This code seems tighter. But unfortunately, the view will give me an error "Undefined variable: name".
Is there any way to achieve this with Laravel?
UPDATE: Another option, as stated in some answers is using compact.
$context = compact('name', 'surname', 'age')
return View::make('myview', $context);
But the problem here is that you have to create all your context variable in one go. And programming is not always so convenient sadly. Sometimes you will want to be adding your elements to the context, as you go progressing through the function.
For instance:
$context = array($name, $surname, $age);
if ($age > 18){
$adult = "He is adult";
array_push($context, $adult);
}
return View::make('myview', $context);
So as you see, if I could use arrays, it wouldnt be a problem because I could push new elements into the $context with array_push. But I can not use arrays that way, unfortunately. And compact wouldn't allow me to push elements inside the context, would it?
You use compact(), a native PHP function (see docs):
compact — Create array containing variables and their values
For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract().
Any strings that are not set will simply be skipped.
For example, to create an array with keys of name, surname, age, with their values respectively:
$name = 'foo';
$surname = 'bar';
$age = 99;
$context = compact("name", "surname", "age");
return View::make('myview', $context);
If you var_dump($context) you would get:
array(3) {
["name"] => string(3) "foo"
["surname"] => string(3) "bar"
["age"] => int(99)
}
Which is what you want to pass into View::make().
Update:
To respond the part of question about using array_push(). I don't think you can use array_push() regardless of compact() anyway. The View::make() still requires a two-dimensional array with key => values. Say you have this array:
$context = array(
'name' => 'foo',
'surname' => 'bar',
'age' => 99,
);
Doing an array_push($context, $adult) would give you:
array(4) {
["name"] => string(3) "foo"
["surname"] => string(3) "bar"
["age"] => int(99)
[0] => string(11) "He is adult"
}
You get [0] => string(11) "He is adult" instead of ["adult"] => string(11) "He is adult". You would not get your expected result in your view using array_push()
To answer "Sometimes you will want to be adding your elements to the context, as you go progressing through the function.", I say there are two ways:
1st approach: Append $context as you go. Similar to your example:
$context = compact("name", "surname", "age");
if ($age > 18) {
$context['adult'] = "He is adult"; // You need to do this way because array_push() does not support setting your own key.
}
return View::make('myview', $context);
Pros: No need to worry whether you have added your variable to the compact() yet.
Cons: To know what is being passed to your view, you need to scan your whole method for key/value that you appended to $context.
2nd approach: Prepare all data then compact them into $context only right before sending to the view.
$name = 'foo';
$surname = 'bar';
$age = 99;
if ($age > 18){
$adult = "He is adult";
}
$context = compact("name", "surname", "age", "adult");
return View::make('myview', $context);
Pros: Single point of compiling view context. You can easily see all variables that are compacted and sent to the view.
Cons: Misspellings are harder to detect. compact() can become really long if you are passing a lot of variables.

Why can I not echo the value of this multimensional array in PHP?

This is so incredibly basic that I am totally baffled as to why it doesn't work. I have an array called $elements, and I want to just echo out one of the values.
I use NetBeans as an IDE, and if I use that to examine the contents of the multidimensional array in question, it looks like this:
So far as I can tell, everything looks normal. It is a multidimensional array, where the first level is numbered "0", and the second level has four named entries.
I just want to echo the value of "parameters", which is a string.
However, this code outputs nothing:
echo "This is the value of 'parameters': " . $elements[0]['parameters'];
Have I got this most basic code wrong in some way?
This is what I get if I do var_dump($elements):
array(1) { [0]=> object(Element)#3 (4) { ["type":"Element":private]=>
string(4) "Text" ["resource":"Element":private]=> string(1) "0"
["parameters":"Element":private]=> string(209) "IP1 111.111.111.111
IP2 222.222.222.222 IP3 333.333.333.333 IP4 444.444.444.444 IP5
555.555.555.555 IP6 666.666.666.666 IP7 777.777.777.777 IP8 888.888.888.888 IP9 999.999.999.999 IP10 111.111.111.112" ["parent":"Element":private]=> NULL } }
... and this is the output from print_r($elements):
Array ( [0] => Element Object ( [type:Element:private] => Text [resource:Element:private] => 0 [parameters:Element:private] => IP1 111.111.111.111 IP2 222.222.222.222 IP3 333.333.333.333 IP4 444.444.444.444 IP5 555.555.555.555 IP6 666.666.666.666 IP7 777.777.777.777 IP8 888.888.888.888 IP9 999.999.999.999 IP10 111.111.111.112 [parent:Element:private] => ) )
Your var dump is saying that element 0 is an object, so you will need to access it like so:
echo $elements[0]->parameters;
The problem is that from your dump, the parameters element is marked as private, so you will not be able to access it.
Solutions are:
Change parameters to public
Write a getter (getParameters()) and use that method to get your parameters.
Entry 0 at $elements is not just an array of attributes it's a class Element instance so in order to access its properties do something like:
echo( $elements[ 0 ]->parameters );
Although the parameters field seems private so you'd better add an accessor method to the object like getParameters() which would be public and return the value of parameters.

Categories