FreshPro
FreshPro

Reputation: 873

Push an element at the end of an array

I have an array called result which I generate like this

 while something
           $result[] = $row;
           array_push($result,$row['fld_ConsumptionValue'] * $energy_type_unit_price) // this won't do 
    endwhile

$result array is filled with db records. What I wanna do is to push another value I calculated like above. output is like this:

    result -> Array[6]
    [0] -> Array[34]
    [1] -> Calculated Value For 1st Record
    [2] -> Array[34]
    [3] -> Calculated Value For 2nd Record
...
...
...

What I'm trying is to get this output

 result -> Array[6]
    [0] -> Array[35]
    [1] -> Array[35]
...
...

What am I doing wrong?

Upvotes: 2

Views: 112

Answers (3)

Amaan Iqbal
Amaan Iqbal

Reputation: 761

The simplest way to do is $array[] = $var;

In your case $result[] = $row['fld_ConsumptionValue'] * $energy_type_unit_price;

Refer http://php.net/manual/en/function.array-push.php for details

Hope it helps

Upvotes: 1

u_mulder
u_mulder

Reputation: 54796

This is it:

while something
    // add new key to `$row`
    $row['someKey'] = $row['fld_ConsumptionValue'] * $energy_type_unit_price;
    // add `$row` to `$result`
    $result[] = $row;
endwhile

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

You don't need to do this, instead do it in the simple way:

$result[] = $row['fld_ConsumptionValue'] * $energy_type_unit_price;

The above will add the value to the end of the array. If you want to use the array Array[34], add that then. Not sure how do you generate that array with 34 items. Or if I get it right, you gotta do this:

$row [] = $row['fld_ConsumptionValue'] * $energy_type_unit_price
$result[] = $row;

The above adds the new one to the $row and you add all the 35 to the main $result.

Upvotes: 3

Related Questions