0

This is an array,

$array = array(
'one' => 1,
'two' => 2,
'three' $array['one'] + $array['two']
);

It's get an error, why?

0

2 Answers 2

1

Because $array does not exist before the end of your declaration. You simply cannot define an array on such a recursive manner since you refer to a non-existing resource.


This is a working variant. Indeed, not very convenient, but working:

<?php
$array = [
  'one' => 1,
  'two' => 2
];
$array['three'] = $array['one'] + $array['two'];

var_dump($array);

The output obviously is:

array(3) {
  'one' =>
  int(1)
  'two' =>
  int(2)
  'three' =>
  int(3)
}

The only really elegant way around this requires quite some effort:

You can implement a class implementing the ArrayAccess interface. That allows you to implement how the properties should be defined internally (for example that sum), whilst still allowing to access these properties via an array notation. So no difference to an array at runtime, only when setting up the object. However this is such a huge effort that I doubt it is worth it in >99% of the cases.

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

Comments

0

You're using a variable which is being declared, its value value is not know yet. Here is how you should write it:

$array = array(
'one' => 1,
'two' => 2,
);
$array['tree'] = $array['one'] + $array['two'];

Comments

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.