Welcome to WebDesignForums.net!
You're currently viewing WDF as a guest. By registering for a free account, you'll be able to participate with other members in our friendly community. Being a member allows you to ask questions and get answers for those troublesome web development tasks!

In addition, as a member you'll be able to post your websites up for review. Using our unique website review system you can gain some amazing feedback from some of the best web developers around. This is a completely free service to all registered members.

Ready to register yet? Registration is 100% free. Click Here To Join Now!

PHP - The Basics

Discussion in 'Coding Articles & Tutorials' started by Danny[MLWA], Jun 24, 2009.

  1. Offline

    Danny[MLWA] Member

    Message Count:
    109
    Likes Received:
    3
    Trophy Points:
    18
    Location:
    Goldsboro, North Carolina, USA
    From what I've seen, many web designers and developers do not know that much about PHP or choose to use proprietary Server Side Scripting like ASP, however I hope to make it a little easier by sharing my knowledge about php. This is a simple tutorial designed to get one started in php, it is no technical manual, it is only designed to help people "grasp" the concept of php.

    Rules of Thumb
    Like html, in php when you open something, you have to close it, but really the only thing that is unlike html, is the fact lines have to be terminated with the semi colon.
    PHP:

    <?php 
    // Opened PHP
    $whatisthis 'this is a string defining $whatisthis which all totaled up, is a line'// And terminated with ;
    // Closing PHP
    ?>
    Variables and Strings
    This is the most important part of PHP, variables! Once you have this part down pat and in your head, the ball is officially in your court. A variable is like in algebra class, the x -- 1+x=y, where x is ? Well if you make x 1, then the outcome of y changes.. changing y also changes the outcome of x. Like in algebra, these variables must be defined. A valid variable starts with the dollar sign ($) and contains alpha-numeric characters, EXCEPT it cannot contain spaces and it CANNOT begin with a number.
    PHP:

    $a_123 
    "somevar"// Good variable
    $abcde "somevar"// Good variable
    $1_abc "somevar"// NO GO (can't begin with a number)
    $abc def "somevar"// NO GO (can't contain spaces)
    $a#ddf = "somevar"; // NO GO (can't contain special characters)
    Now the "basic" built-in functions to get you going on some puliminary programing:
    echo() - This will print the string defined between the prenthisis.
    PHP:

    echo('My Name is Danny'); // Would show in a web-page, My name is Danny.
    $name = ('Danny');
    echo(
    "My name is $name"); // Would show in a web-page, My name is Danny.
    As you saw above, a string is a line of code that usually defines a variable or constant.
    PHP:
    ("This " .  $is " a string")
    But of course, $is is not defined, but is just for demonstration purposes only.

    As you can see a string is broken like that to show strict translation of the variable, usually when there is text "hugging" the variable or the string is set to flexible (for lack of words) interpretation (by using "s instead of 's) where strict interpretation is extremely literal by using the single quote.
    PHP:

    $strict 
    "flexible"
    $string = ("This is a $strict interpretation."); // $string is, This is a flexible interpretation.
    $string = ('This is a $strict interpretation.'); // $string is, This is a $strict interpretation.
    You can force adding strings and variables together by breaking the string and adding the period in-between to adjoin them as such:
    PHP:
    $string = ('This is a '$strict ' interpretation'); // $string is, This is a flexable interpretation.
    Even though its strict, you broke the string and ajoined the variable from within. This is very useful for tricky strings like:
    PHP:

    $age 
    4;
    $string = ("My age=$age"); // $string is, My age=$age
    Because $age is "hugging" the = or anything other than a space, it is not interpreted as a variable unless the string is broken like so:
    PHP:

    $age 
    4;
    $string = ("My age=" $age); // $string is, My age=4
    Now lets talk about the basic "SUPER GLOBAL" variables; these are usually variables built into PHP or variables translated by the string proceeding the file in the URL after the ?... For instance, yourfile.php? -- After the ? you can start tacking on variables to inject into PHP separated by the ampersand (&), for example:
    yourfile.php?age=4&name=Danny&page=index
    You would call these in php as:
    PHP:
    $_REQUEST['thevariable']
    So the URL string I mentioned above could be echoed in the php file as such:
    PHP:

    echo("My name is $_REQUEST['name'] and I'm $_REQUEST['age'] years old.  You are viewing the $_REQUEST['page'] page.");
    This would display:
    Code:
    My name is Danny and I'm 4 years old.  You are viewing the index page.
    Now in strings you can perform basic math... addition, subtraction, multiplication, and subtraction. These of course use the basic signs as well and are simply done in "reverse" from the math classes you've taken as such:
    PHP:

    $five 
    5;
    $six 6;
    $result $five+$six// $result is, 11
    The wrong way:
    PHP:

    $five 
    5;
    $six 6;
    $five+$six $result// returns an error, result is undefined as you're declaring the sum of $five and $six as $result.
    Now you have enough knowledge to build your own calculator!

    Create addition.php and edit it in your favorite text editor:
    PHP:
    <?php
    // My first php addition calculator!
    echo($_REQUEST['var1']+$_REQUEST['var2']);
    ?>
    Upload it to a web server and define after addition.php?var1=SOMENUMBER&var2=SOMEOTHERNUMBER

    Congratulations, this concludes part 1 of the tutorial! =)

    Conditional Statements
    Fun fun fun! Conditional if-elseif-else statements... Quite literally, that's what they are... These statements are telling php to do something if a condition is true, if not do something else...

    IF - If the statement is true....
    ELSEIF - Must DIRECTLY proceed the IF statement and provides an alternative match.
    ELSE - if the if statement and elseif statements are false, finish up with this.

    In these statements you have several operators at your disposal, but for explaination sake, we'll talk about a few...
    == - Is equal to
    != - Is not equal to
    <= - Is less than, or equal to
    >= - Is greater than, or equal to
    < - Is less than
    > - Is greater than

    Now you have conjunctions -- symbols you add between statements within the same statement:
    && - AND ex. (conditional && conditional)
    || - OR ex. (conditional || conditional)
    Lets give this a practical try...

    PHP:

    $name 
    'Danny';
    if(
    $name == 'Danny')
    {
    echo(
    'My name is Danny!');
    }
    elseif(
    $name == 'Tom')
    {
    echo(
    'My name Tom!');
    } else {
    echo(
    'My name is neither Danny or Tom!');
    }
    Now if $name is "Danny" then the first statement would be true, and would print, My name is Danny!. If $name is "Tom" then the second statement would be true and would print, My name is Tom!. If you place anything else as $name, it would fault to the else statement of, My name is neither Danny or Tom!.

    Lets give that calculator a try again... This time, lets provide a few upgrades!

    create the file, calculator.php, and edit it with your favorite text editor...
    PHP:

    <?php
    // My second calulator program for PHP.

    // Lets start by determining whether we're going to be adding, subtracting, multiplying, or dividing...
    if($_REQUEST['calc'] == 'add')
    {
    // Addition calculator
    echo($_REQUEST['var1']+$_REQUEST['var2']);
    }
    elseif(
    $_REQUEST['calc'] == 'subtract')
    // Subtraction calculator
    echo($_REQUEST['var1']-$_REQUEST['var2']);
    }
    elseif(
    $_REQUEST['calc'] == 'multiply')
    // Multiplication calculator
    echo($_REQUEST['var1']*$_REQUEST['var2']);
    }
    elseif(
    $_REQUEST['calc'] == 'divide')
    // Division calculator
    echo($_REQUEST['var1']/$_REQUEST['var2']);
    } else {
    echo(
    "Woopsie, please define calculator.php?calc=...");
    }
    ?>
    Congratulations, this concludes part 2 of the tutorial!

    Functions and Loops
    Now for our last part, functions and loops, and definitely the most confusing or the most fun, however you wish to view it, but we'll start with the easy part.. Functions.

    A function is a pre-built set of instructions to be called when ever you please! You can inject variables directly into the function from the place of use. You "define" your function by first starting a line with the word function, and following it up with a space, the function name and the parenthesis with any variables you want injected within those parenthesis.
    PHP:

    function MyFirstFunction($yay)
    {
    // this is my first function and it does absolutely nothing, whatsoever... yet.
    }
    Everything like with the conditionals between the brackets {} applies to this function and is included into it. You would call your function like it looks but without the "function" preceeding it.
    PHP:
    echo MyFirstFunction("nothinghere");
    This would inject into the function the variable $yay as, nothinghere. Lets complicate things a little, try and hang on...
    PHP:

    echo printName("Danny"); // returns, My name is Danny.
    function printName($name)
    // Danny was injected into the $name variable from the function call above.
    $return = ('My name is ' $name '.');
    return 
    $return;
    }
    Now you should have functions down pat, they're really not that hard, though they can get complicated... Just remember that variables have to be defined within the function or injected.

    Before we jump right into a function you need to know the basics about arrays. Array is a gruesome sounding word, but it is quite simple. Imagine your operating system, in a folder you have files... an array is about the same thing... You have the array, and you have records in that array.

    $array = array('record1', 'record2', 'etc');

    You can "associate" the arrays with words instead of the default numbering system by declaring them in the array as such:
    $array = array('firstrecord' => 'record1', 'secondrecord' => 'record2); // and so on.

    You can also define arrays, "strait up" or forcefully...
    $array[0] = 'My name is Danny';
    $array[1] = 'My name is Tom';
    $array[2] = 'I have no name!';

    Now you know the basics of arrays, we can move right into loops!

    Loops are a little more complicated but we'll do the simplest loop now, you can learn other loops by looking them up on Google. The loop we're going to discuss is a for loop... there are 3 conditions to a for loop, 1) Initialization, 2) Condition, 3) Counter.

    for(initialization; condition, counter) is the proper syntax.

    Lets try this loop with the array above...
    PHP:

    for($i=0;$i<count($array);$i++)
    {
    echo(
    $array[$i]);
    }
    Now lets study this a second... Notice the $i is the number of that array above. So $i=0, this is where the numbering starts, and it will then keep looping until it reaches the last record in the $array. (you can make it count down by doing the opposite for($i=count($array);$i>=0;$i--) which will count down!)
    With the example above, you'll notice that $i starts at zero, so the first record will be $array[0] which is My name is Danny, and will then show the next record $array[1], and so on.

    That concludes this tutorial! I hope you've learned something interesting and if you've enjoyed the tutorial let me know! Maybe I'll start some php-mysql tutorials and really get knee-deep in creating some truly dynamic pages =).


    Zboost, RDesignista and Alanna Baxter like this.
  2. Offline

    smoseley Administrator

    Message Count:
    9,727
    Likes Received:
    192
    Trophy Points:
    63
    Location:
    Boston, MA
    Very nice write-up!


  3. Offline

    salonline WDF Addict!

    Message Count:
    189
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    bangalore
    Very beautifully explained and presented. Thanks for the same.


  4. Offline

    aburningflame New Member

    Message Count:
    483
    Likes Received:
    0
    Trophy Points:
    0
    Nice tutorial...the only criticism i have is the use of $_REQUEST.
    Very rarely should you use request.

    Use the proper super global: $_POST, $_GET, $_SESSION, $_COOKIE.

    That way you're SURE where your value is coming from.
    I know there's a processing order when using $_REQUEST, but i still feel safe knowing that if i use $_POST there is no chance the value isnt coming from a form...if you use $_REQUEST...who knows where the value is coming from (someone can probably circumvent the processing order somehow)... BUt other than that, great tutorial.


  5. Offline

    Ganners Active Member

    Message Count:
    415
    Likes Received:
    90
    Trophy Points:
    28
    Gender:
    Male
    Location:
    United Kingdom
    Very good! Some points:

    Code:
    $a#ddf = "somevar"; // NO GO (can't contain special characters)
    
    Above isn't completely true (though I'd advise to keep this convention), you can't have some special characters but there are even more than you can have.

    Code:
    $age = 4;
    $string = ("My age=$age"); // $string is, My age=$age
    
    In this instance, instead of concatenating outside, you could simply do:

    Code:
    $age = 4;
    $string = ("My age={$age}"); // $string is, My age=4
    
    It is recommended you wrap all variables in braces within double quotes.

    For users using php 5.4(.1 ?), you have a better way to define arrays which is how it is in many languages.

    Code:
    $array = ['firstrecord', 'secondrecord', 'thirdrecord'];
    


Share This Page