Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return object value with space in key

Tags:

just come across something I've never came across before. I have a value in my table "Device Vendor" and i am returning the data os an object.

usually I would call $ob->var_name but obviously $ob->Device Vendor will not work.

How do I return the value?

Regards

like image 682
Phil Jackson Avatar asked Jul 11 '11 11:07

Phil Jackson


People also ask

How do you access an object with space in the key?

Use bracket notation to access a key that contains a space in an object, e.g. obj['my key'] . The bracket [] notation syntax allows us to access an object's key, even if it contains spaces, hyphens or special characters.

Can you have spaces in object keys?

We typically write JavaScript object properties using camelCase, without spaces, but you can use spaces in keys if you prefer. Just be sure to include quotation marks to specify the string you're using as the object key.

Can JSON object keys have spaces?

Whitespace (Space, Horizontal tab, Line feed or New line or Carriage return) does not matter in JSON. It can also be minified with no affect to the data. Object literal names MUST be lowercase (ie – null, false, true etc).


2 Answers

You use the following syntax

 $ob->{'Device Vendor'} 
like image 172
Paul Dixon Avatar answered Oct 16 '22 17:10

Paul Dixon


The syntax is this:

$ob->{'Device Vendor'} 

I'm having a hard time trying to find an explicit reference to this in the PHP manual. I'm afraid that it needs to be inferred and you can only do so if you already know the answer. At Classes and Objects-> Properties they say:

Class member variables are called "properties". [...] They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration.

The rules that applies now is Variable variables:

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a1 then the parser needs to know if you meant to use $a1 as a variable, or if you wanted $$a as the variable and then the 1 index from that variable. The syntax for resolving this ambiguity is: ${$a1} for the first case and ${$a}1 for the second.

We are basically abusing variable variables so we can use a space.

like image 27
Álvaro González Avatar answered Oct 16 '22 17:10

Álvaro González