Jump to content
MakeWebGames

The Basics of PHP


Razor42

Recommended Posts

After looking around many websites and collecting different types of information I have created my own basics of PHP tutorial.

The first thing to know in PHP is obviously the open & close tags.

<?php this is the open tag for a php code, this lets the server know that a php code is about to begin.
?> this is the close tag for a php code, this lets the server know that the php code has now ended.

Everything in between the open tag and the close tag will be read as PHP code. The <?php tag can also be phrased as <? if desired.

The next thing to learn about is how to place comments within your code which will be ignored by the server and not displayed on your webpage. Comments are used for various reasons, they can be used as a refferance to what the code is doing so that when you go back later to edit the code you will know what everything is doing and what to edit. They can also be used if you are wanting to share the code with other people and want them to know whats going on at each part of the code and also if you want to include your name and terms of services within a code, there are two types of comments:

//This is a comment to be used one a single line.

/*
Using the method you can create
much larger comments which can go other mutiple lines and will still all be commented out
*/

 

Now that we know what the open & close tags are and also how to place comments into our codes now its time to move onto the echo & print statment. What this does it it outputs whatever you tell it to do and displays it as text on your webpage. There is a lot of debate about which is better to use or if there is any difference at all. Apparently in very large programs that are simply outputting text the ECHO statement will run slightly faster, but for the purposes of a beginner they are interchangeable so use which one you will find most comfortable to remember.

 

<?php
print "hello"; //this will display the text hello onto your website, notice that the hello is in quotation marks, when using the print or echo statment you must place the text you want to be displayed in quotation marks.
echo "hello";//this will display the text hello on your website just like the print statment.
?>

notice that each line ends with a semicolon, whenm your PHP code is longer than one line then you must seperate each line with a semicolon.

The next thing we are going to move onto are variables, variables are used to hold expressions or values. There are a couple of things that we must remember abiut variables, the first thing is that they must start with a $ sign which is then followed by the name of the variable. The second thing is that the name must begin with a letter the underscore character. The thrid thing is that the variable name should not contain spaces and only contain letters, numbers and the underscore charatcer. The final thing is that variable names are case sensative ( $My and $my would be too different variables).

 

$MyCar = "Audi"; //This creates a variable. The variable MyCar will now hold the value "Audi". Notice the quotation marks again.
$Age=7; //This also creates a variable. notice that there are no quotation marks as they must only be used on a text value.

 

Now we can use this variable to tell people what car we drive and learn to use variables with the print/echo statment:

$MyCar = "Audi";
print "Hello, I drive a $MyCar; //This will display Hello, I drive a Audi onto your webpage

 

Now we have the basics of Variables covered we can move onto Arrays. While Variables can hold one single piece of data, an array can hold a string of related data. An array can hold all your variable values under a single name and you can access the values by referring to the array name. Each element in an array has its own index so it can be found easily.

$friend[0] = "Justin"
$friend[1] = "Paul"
$friend[2] = "John"
$friend[3] = "Garry" //this creates an array
print "My friends names are " . $friend[0] . ", " . $friend[1] . ", " . $friend[2] . ", ". $friend[3]; //this will print all the names of your friends from the array.

That array is arranged using integers as the key ( the key is the information between the [ ] brackets).

Arrays can also be arranged using text as the key:

$age["Justin"] = 45;
$age["Paul"] = 20;
$age["John"] = 50;
$age["Garry"] = 30; //this states another array using text as the key.
print "Paul is " . $age["Paul"] . " years old"; //this will display Paul is 20 years old.

 

Now we have the basics of Arrays its the time to move onto IF ELSE statements. Very often when you write code, you want to perform different actions for different decisions, you can use the IF ELSE statements to do this. Below is an example of an IF statement that would apply a senior's discount. If $over65 is false, everything within the {brackets} is simply ignored:

$over65 = true;
$price = 1.00;
if ( $over65 ) //this is the start of an IF statment. if over65 is false then everything in the brackets below is ignored.
{
$price = .90; //this states what the price will be if over65 is true.
}
print "your price is $" . $price; //this will print your price. If over65 is true it will output your price as .90 but if false then it will output as 1.00.

The if statment is used to execute some code if only the specified condition is true. Notice that there is no ..else.. in this syntax. The code is executed only if the specified condition is true.

However, sometimes just the IF statement isn't enough, you need the ELSE statement as well. When using just the IF statement the code within the brackets either will (true) or will not (false) be executed before carrying on with the rest of the program. When we add in the ELSE statement, if the statement is true it will execute the first set of code and if it is false it will execute the second (ELSE) set of code. Here is an example:

$over70 = true;
$cost = 3.00;
if ( $over70 ) //this states another  IF statment. If false then everything in these brackets will be ignored.
{
$discount =.90; //This will be discounted from your price if over70 is true.
print "you have recieved our seniors discount. Your price is $" . //this will tell you your price if over 70 is true.
$price*$discount; //this will multiply your price by your discount if the over70 is true.
}
else // This states an else statement. If over70 is true then everything within these brackets will be ignored.
{
print "sorry you dont not qualify for our senior discount. Your price is $" . //this will display your price and tell you that over70 is false.
$price;
}

 

This is my basics of PHP tutorial, I hope you like it and I hope you like it and also that it helps people learn :)

Edited by Razor42
Link to comment
Share on other sites

Wrong.

 

<?php
echo 'Hello world!';
// No closing tag

 

Is totally valid, runs and in my opinion, better.

[color=#666666]The <?php tag can also be phrased as <? if desired.[/color]

To add:

 

php -r "echo 'haai';"

 

PHP can run without any tags, via the -r option.

Link to comment
Share on other sites

notice that each line ends with a semicolon, whenm your PHP code is longer than one line then you must seperate each line with a semicolon.

Not true, see:

$variable = ('this') 
. 'is' 
. 'my
multi-lined
string';

 

Also:

$assignment = (empty($other_variable)) ?
                    false :
                    true;

 

And...

$long_ass_string = print <<<STR
b
l
a
h
d
i
b
l
a
h
d
i
h
u
h
?
STR;

 

There's quite a few other cases.

The proper wording should be:

A semi-colon is used to separate statements.

And also, it's called an delimiter.

Edit: Oh yes, and semi-colons aren't optional.

Edited by Spudinski
Link to comment
Share on other sites

I wouldn't advise to use short tags either, since these can be turned off within the PHP config, rending your scripts error prone.

 

[highlight]<?= is Always On[/highlight]

Regardless of the php.ini setting, short_open_tag, <?= (open PHP tag and echo) will always be available. This means that you can now safely use:

<?=$title?>

…in your templates instead of…

<?php echo $title ?>

 

http://net.tutsplus.com/tutorials/php/php-5-4-is-here-what-you-must-know/

Link to comment
Share on other sites

Not only does it matter if you use echo or print lets not leave out the double quotes and single quotes ....

Double quotes should not be placed on a string that has no $vars... because what it is doing is taking time to parse that string. It's much easier and faster to use single quotes when there is no $vars present if you are using double through out your script... over all it's a persons preference on what they feel comfortable using, however if your wanting your stuff to come up faster then single quotes should be used in an echo statement in IMO.

Link to comment
Share on other sites

PHP > 5.4 only.

As far as I am aware, 5.3 is still the de facto standard, in a lot of hosting enviroments.

That and should you wish to support legacy versions of PHP, it's wise to use the primary methods.

@OP: Great start, work on it more and it could become a handy little guide.

@Lucky: Please stop with the whole "single-quotes is faster", the speed difference, is negligible that it isn't really an issue. Use whatever you wish, whichever you find easiest (or quick in terms of pressing the specific keys on your keyboard).

@Additional (at Lucky): There's only a handful of situations where using print or echo matters over each other. PHP Manual - echo

Edited by Djkanna
Link to comment
Share on other sites

@Lucky: Please stop with the whole "single-quotes is faster", the speed difference, is negligible that it isn't really an issue. Use whatever you wish, whichever you find easiest (or quick in terms of pressing the specific keys on your keyboard).

@Additional (at Lucky): There's only a handful of situations where using print or echo matters over each other. PHP Manual - echo

Why should I stop, since when can't I have an opinion, and state the obvious, no need for your link this one explains the routine of quotes... http://php.net/manual/en/language.types.string.php

 

To each their own... Better to practice the right way then the wrong way... just saying, why parse a string without a $var in it... does not makes sense, so thus is why I stated what I did, and yes it is faster, single quotes...

Link to comment
Share on other sites

Why should I stop, since when can't I have an opinion, and state the obvious, no need for your link this one explains the routine of quotes... http://php.net/manual/en/language.types.string.php

To each their own... Better to practice the right way then the wrong way... just saying, why parse a string without a $var in it... does not makes sense, so thus is why I stated what I did, and yes it is faster, single quotes...

My link was at the print vs echo, not at the quotes.

As for what I said, wasn't mean't to be taken as 'you are not allowed an opinion', it was meerly stating that the speed difference is so little the fact that your using " single is faster than double so use single " is silly.

Like I said last time, use whichever you find easiest, but don't worry about the speed difference, as 99.8% you won't see a negative or a positive effect from using one or the other.

Also on that note there is no right or wrong way.

Link to comment
Share on other sites

It's the same as == vs === comparison.

== typecasts, and then converts, === doesn't(eg. int 1 != string 1).

But is there a speed difference? Of course there is, there always is.

Will you see the difference? Depends.

If you compare two 500mb sets of data, there'll be a clear difference.

Same with echo, and single quotes.

Also, debating it isn't silly(sorry Djk) - high performance optimizations is one of the key parts in programming.

If there's a faster/better/more efficient way of doing something, I'm sure as hell going to find it AND point it out.

Link to comment
Share on other sites

Also, debating it isn't silly(sorry Djk) - high performance optimizations is one of the key parts in programming.

If there's a faster/better/more efficient way of doing something, I'm sure as hell going to find it AND point it out.

Now here I would agree if it wasn't for the most overused and insignificant debate, of single quotes vs double quotes.

I'd like to make it clear, I'm not disagree-ing with it, I just don't think in everyday use the difference in which using one or the other is an issue, therefore on a "Basics of PHP" guide, I don't think telling someone to use single quotes because it's faster is appropriate.

So yes in this situation I think debating on which you should use is silly.

Link to comment
Share on other sites

I think the biggest problem comes from new coders who do not completely understand what they're reading.

Some might see "Single quotes are faster/more correct/whatever" and think "I need to go through every page and re-do all of my quotations, else it will slow my server down and oh noooo's!"

In this case, again, the difference is so negligible in the everyday circumstance, such a debate only causes unwarranted worry on the part of the reader.

Link to comment
Share on other sites

I think the biggest problem comes from new coders who do not completely understand what they're reading.

Some might see "Single quotes are faster/more correct/whatever" and think "I need to go through every page and re-do all of my quotations, else it will slow my server down and oh noooo's!"

In this case, again, the difference is so negligible in the everyday circumstance, such a debate only causes unwarranted worry on the part of the reader.

Balls, any chance of me hiring you to do all my explaining for me? :o

Link to comment
Share on other sites

lol...

still though why parse a string with no variable present ??? anywho do what you feel comfortable with. I like to do things the correct way as taught.

When it comes to such a minimal speed difference, I don't think it's about being "correct." It's personal preference. Everyone has a style of coding, and most of the time, there will be at least one unnecessary piece of that style you could pick apart if you really tried, but does that mean they're going to change how they do it? Not likely.

Link to comment
Share on other sites

I don't think there is a completely right way, and a completely wrong way as long as it work. Programming is also matter of taste. So some prefer concatenations, other use the string parsing or use formatting functions. Is one or the other way wrong? No as all 3 will make the same result. Sure if you are after extremely high speed, then maybe you would look into optimizing your code, but then, the best option is to leave PHP to something faster like Java, .NET or even plain C / C++ code.

Link to comment
Share on other sites

I use a few methods, depending on what's needed(and how lazy I am):

 

Implode:

$my_formatted_list = implode(', ', array('Item 1', 'Item 2', 'Item 3'));

This method is very useful for displaying a list of data with the additional need for a separator.

Mostly database data are aggerated like this.

Formatting:

$ff = sprintf('Form feed: %c', 0x0C);
$formatted = sprintf('Hello %s, you current balance is %.2f', $a::name, $a::balance);

Useful, everywhere - though I mostly use it to build up resource strings, like URLs and dsns.

Concat:

$formatter = 'This is a ma' . 
                 'ssively long' .
                 'string.';
Link to comment
Share on other sites

It's the same as == vs === comparison.

== typecasts, and then converts, === doesn't(eg. int 1 != string 1).

If I read the documentation on this correctly ...

X is a decimal in a table field and it's value is 5.00

Y is an int in a table field and it's value is 5

X==y returns true

X===y returns false

but if both X and Y where decimal and you used === it would then return true.

Is that how these two work? And which would be faster to use?

Link to comment
Share on other sites

Do a benchmark yourself to see which is faster. However, I doubt it will be such a huge difference and therefore use the appropriate way to do it, without yet really caring about the speed difference. That would be my choice.

I wouldn't even know how to do a benchmark test.

And did I understand correctly how they work?

Link to comment
Share on other sites

If I read the documentation on this correctly ...

X is a decimal in a table field and it's value is 5.00

Y is an int in a table field and it's value is 5

X==y returns true

X===y returns false

but if both X and Y where decimal and you used === it would then return true.

Is that how these two work? And which would be faster to use?

I'll first explain how they work, and then you can guess which is faster.

PHP has loose or dynamic typing(some might argue hybrid typing as well).

With static/strongly typed programming languages such as C, you will need to definite the "type" of data the variable is going to hold before you utilize it, i.e. "double balance = 2.00".

PHP is loosely typed, which means that you do not have to do this - but, there are still a presence of different data types.

This is the reason why type-casts exist, to convert data types.

I'll do a quick representation of primitive data types, I'll use the number 5.

110101 (Binary, 0b110101 since PHP 5.4) -> 0x53 (Heximal, prepends 0x/X) -> 065 (Octal, prepends a 0) -> 53 (Decimal, will need to be converted using PHP dec2* functions) -> 5 (Integer) -> "5" (String)

 

Now that we have that out of the way, let's look at comparison operators.

PHP defines == as: Equal (after "type juggling").

PHP defines === as: Identical (no "type juggling").

Type juggling is the processes of converting one data type to the other for comparison.

With == this is present, so (string) "1" == (int) 1 is TRUE, while (string) "1" === (int) 1 is FALSE.

Even (double/float) 1 === (int) is FALSE, as the actual representation of "double 1" is 1.00*.

Does this explain it a little bit better?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...