user1867787
user1867787

Reputation: 9

Can PHP do this?

Can PHP do This.

I have multiple array like this :

$x[1][2][3] = 10;
$x[1][2][4] = 5;
$x[1][2][3] = 2;

When I'm using print_r($x) The result is :

Array
(
    [1] => Array
        (
            [2] => Array
                (
                    [3] => 2
                    [4] => 5
                )

        )

)

I want to do this :

Array
(
    [1] => Array
        (
            [2] => Array
                (
                    [3] => 12
                    [4] => 5
                )

        )

)

Maybe you know the function or script for get result that I wont.

Thank's for your help..

Upvotes: 0

Views: 104

Answers (3)

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41925

What you want to do is incrementing:

@$x[1][2][3] += 10;
@$x[1][2][4] += 5;
@$x[1][2][3] += 2;

@ are for suppressing errors. It would be better and more explicit to initialize your indexes like so:

$x[1][2][3] = 0;
$x[1][2][4] = 0;

$x[1][2][3] += 10;
$x[1][2][4] += 5;
$x[1][2][3] += 2;

Upvotes: 0

Fabian Blechschmidt
Fabian Blechschmidt

Reputation: 4141

You can do this:

$x[1][2][3] += 10;
$x[1][2][4] += 5;
$x[1][2][3] += 2;

The problem is, if the key is not defined, you get a NOTICE. So you have to check before, wether the key exists for example with if(!isset($x[1][2][3])) {$x[1][2][3] = 0;}

Upvotes: 1

gustyaquino
gustyaquino

Reputation: 767

Add ?

$x[1][2][3] = 10;
$x[1][2][4] = 5;
$x[1][2][3] = $x[1][2][3] + 2;

Upvotes: 1

Related Questions