user1467788
user1467788

Reputation: 5

Is it possible to push a value into array based on its key

Is it possible to push a value into array based on its key but actually add to the key.

For example

$data = array();

    $data[0]= 12;
    $data[1]= 1;
    $data[2]= 2;
    $data[3]= 56;
    $data[4]= 78;

array_push($data, 0,23);

so the output would be

$data[0]= 35;   (12+23)
$data[1]= 1;
$data[2]= 2;
$data[3]= 56;
$data[4]= 78;

Upvotes: 0

Views: 89

Answers (2)

Blender
Blender

Reputation: 298106

Instead of using =, you can use += to append a value to a variable:

$data[0] += 23;

This code is equivalent to this:

$data[0] = $data[0] + 23;

You can see the output here: http://codepad.org/bNruNNFe

Upvotes: 3

jpiasetz
jpiasetz

Reputation: 1772

Why not $data[0] += 23?

Or

Why not $data[0] = $data[0] + 23?

Upvotes: 4

Related Questions