Sunday, 11 November 2012

echoing with PHP

Printing 'hello world' is the way in which every programmer begins his/her learning and  that is exactly what are we going to do in here.
First open your notepad and type the following code:
                                           <?php 
                                               echo "hello world!";
                                            ?>
and save it as "hello_world.php" do not forget to add double quotations otherwise notepad will append a .txt format after 'hello_world.php' and will become 'hello_world.php.txt' and it will not be executed as a php code.
Then put it inside your web directory( if you are using Easy Php your default web directory is 'www' which is situated inside the easy php folder).Then run it from your web browser.just type http://127.0.0.1/hello_world.php or http://localhost/hello_world.php on the address bar of your browser and it will print 'hello world' as expected.
Now lets make it more interesting.Lets say we want to add two number and echo out its output.
                                             <?php
                                                  $a=5;
                                                  $b=6;
                                                  $c=$a+$b;
                                                  echo  $c;
                                                 ?>
 and run it as http://localhost/filename.php and you will be able to see 11.Now see the difference here we echo out but do not use a double quotation.This is not a mistake, we did it intentionally as we are echoing a variable when we are printing some variable we do not need to double quote it but for strings we double quote it.lets take a look at the example below:

                                              <?php
                                                  $a=5;
                                                  $b=6;
                                                  $c=$a+$b;
                                                  echo " $c";
                                                 ?>
if we do this then the result will be $c because now that we have double quoted it it is no longer a variable, it is now a string( remember a 'string' not 'string variable').


No comments:

Post a Comment