I guess my question is two-fold
In Python if I do this
x = {key: value}
I've created a dictionary
In javaScript if I do the same thing I've created an object
What is that in PHP? It could just be that I don't know the terms
I'm working on a project with laravel. I basically have an sqlite database which I am accessing. This is returning an array of 'objects'[in javaScript terms]. I want to do a foreach loop through the 'objects' in the array and I want to add a new key and value to the 'object'.
Secondly - Sorry I'm not 100 percent certain of the syntax- in php:
$person = [0 => {name: "Jake", age: 22},
1 => {name: "Chris", age: 34}];
Again I'm really sorry about the syntax, I'm receiving the array directly from the sqlite database so it isn't overly important at this stage.
My question is - If I want to add say, a height to each person, how do I do that? Let me rephrase that, I know to loop through the array with a foreach, I just need the command which will allow me to append a new key/value pair to the end of a Dictionary/Object/What they are called in PHP.The result would be:
$person = [0 => {name: "Jake", age: 22, height: "2m"},
1 => {name: "Chris", age: 34, height: "3m"}];
I know it is a super simple question but I'm struggling to find the right questions to ask google. If I am asking the wrong question please enlighten me I've been scratching my head for too long on something that I could do so easily in another language. I really appreciate the help.
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
PHP offers us a special type of array called an Associative Array that allows us to create an array with Key-Value pairs. The syntax for creating an Associative Array is as follows:
Syntax 1: Using array[] constructor
$arrayVariable = array[ key1 => value1, key2 => value2, key3 => value3, ... keyN => valueN, ];
Syntax 2: Using shorthand notation
$arrayVariable = [ key1 => value1, key2 => value2, key3 => value3, ... keyN => valueN, ];
Note:
- The comma after the last Key-Value pair is optional.
- The Key can be of either integer or string type.
- The Value can be of any valid type.
- If the type of Key is other that string or integer, it will be cast to string or integer depending on the type of Key.
Example 1: Using array[] constructor
Output:
Example 2: Using shorthand notation
Output: