Saucy
Saucy

Reputation: 175

PHP Combining array key values (in same array) to create a new key value

Would it be possible to combine an arrays keys to create a new key using the combined key values?

I'm not asking to create a function to combine them, just wondering if it is possible to do something like this (obviously this code doesn't work, just showing what I meant in code):

<?php
$box = array(
    "Width" => 10,
    "Height" => 20,
    "Total" => ($box["Width"] + $box["Height"]),
);
echo $box["Total"]; // would show up as 30
?>

Upvotes: 2

Views: 510

Answers (4)

Yada
Yada

Reputation: 31235

Since you already have 10 and 20 you can write

<?php
$box = array(
    "Width" => 10,
    "Height" => 20,
    "Total" => 10 + 30,
);
echo $box["Total"]; // would show up as 30

Upvotes: -1

Matthew
Matthew

Reputation: 48304

The easy answer is no.

To elaborate: this is precisely what classes are meant to do. Note that you can do what you are trying to do very simply:

<?php
class Box extends ArrayObject
{
  public function offsetGet($key)
  {
    return $key == 'Total' ? $this['Width'] + $this['Height'] : parent::offsetGet($key);
  }
}

$box = new Box(array(
  'Width' => 10,
  'Height' => 20
));

echo $box['Total'],"\n";

Of course $box is not a true array in this example, and as such, cannot directly be used with array functions. See the docs for ArrayObject.

Upvotes: 1

xdazz
xdazz

Reputation: 160903

You need 2 steps:

$box = array(
    "Width" => 10,
    "Height" => 20,
);
$box["Total"] = $box["Width"] + $box["Height"];
echo $box["Total"];

Upvotes: 2

deceze
deceze

Reputation: 522461

No, not while the array is being defined. array(...) is being evaluated first, the result of which is assigned = to $box. You can't refer to $box before the evaluation is finished.

You'll have to do it in two steps, or perhaps create a custom class that can do such magic using methods and/or (automagic) getters.

Upvotes: 3

Related Questions