-3

I have an array of data:

Array ( [0] => stdClass Object 
  ( 
    [name] => admin
    [email] => [email protected] 
    [password] => cxvxvcxvcxv
  )
)

I want to add a new data to this array so the final array looks like:

Array( [0] => stdClass Object 
  ( 
    [name] => admin
    [email] => [email protected] 
    [password] => cxvxvcxvcxv
    [enabled] => true
  )
)

I tried array_merge(), but it gives me result like this:

Array( [0] => stdClass Object 
  ( 
    [name] => admin
    [email] => [email protected] 
    [password] => cxvxvcxvcxv
  )
  [enabled] => true
)

How do I achieve the result I want?

4
  • 4
    Possible duplicate of Adding value to array inside object PHP Commented Jan 11, 2019 at 8:05
  • 2
    you want to add new property to an existing class, not to an array ! Commented Jan 11, 2019 at 8:05
  • 2
    it's object. You can't use array merge Commented Jan 11, 2019 at 8:05
  • @splash58 sorry i updated my question, it's an array with an object inside the first index and I want to add [enabled] => true in my object. Commented Jan 11, 2019 at 8:09

1 Answer 1

0
$myArray[0]->enabled = 'true';

Just add the new field straight into your object and assign the value you want to it. This should do the trick for you.

If you array has multiple nested arrays you will need a loop though. My code will only work for position 0 like you asked.

Sign up to request clarification or add additional context in comments.

2 Comments

will that work if i want to save enabled as a boolean value?
Of course just remove the single quotes if you want to have it in a boolean value. Give it a try. Keep in mind that true is 1 and false is 0. If you want to have it as a word then you can use it like a string as have in my example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.