Add up numbers in PHP?

By Moe Jame Share
Browse the PHP category for more tutorials

Adding up numbers is an important part of programming applications.

1. Create two variables

For example, we created $first_number and $second_number

First you need to create the variable

As of right now, our variables have absolutely no value associated to them. If you run your code as is, you will have a neat “Server Error” page:

What happens if a variable is not set

So in order to produce a result, we need to assign a value to each variable. It can obviously be whatever you want it to be.

2. Assign a value to a variable

For this example, let’s make the value of the $first_number variable to be equal to 2, and the $second_number variable to be equal to 5. In order to do that in your code, you need to assign a value to each variable. You do that by simply adding the following right after your variable  = “{value}”; and replace the {value} with whatever you want the value to be. It could be a string, or an integer.

In the case strictly of integer, you can attach a value either with or without the quotes surrounding it (“value” or value both work)

Without quotes surrounding {value}:

Assign a value to each variable

Or with quotes “{value}”:

Add quotes around your number will work too

Test it yourself. Both version work.

3. Create a $sum variable

Simply add $sum after

Create a $sum variable

But just like before, since $sum is not set, if you try to run that code, you will get a server error.

We want to add up $first_number variable which is equal to 2, and the $second_number which is equal toand we want that sum value to be carried in our $sum variable which should be equal to 7

To do that, we just write $sum = $first_number + $second_number

Sum it all up

4. Display the $sum variable value

Now the last step is to display the value that the variable $sum hold using the echo function.

Echo the $sum value

This is the output:

Output of our script in our browser

5. Done

Keywords

Add UpAdditionSum

More PHP Tutorials

How to Add up numbers on PHP

How to Automatically display the current year in footer on PHP

How to Display text using a variable on PHP

How to List files in a directory on PHP

Follow us on Twitter Subscribe to our Feeds Become a Fan on Facebook

3 Responses and Counting

Guest 09.06.2010

i can has cheeseburger?


I was confused but this clears it all up, thanks :D


I need this stuff right now! Anyway, I had hard times finding the right steps but I think this worth all the long hours that I wait.


Add your comment

(Spamcheck Enabled)



New Tutorials in your inbox!

Follow Us

RSS
facebook
twitter