PHP Basics

Welcome to the PHP Basics thread. This is the, well, the basics - a place to look up the most common new programmer questions that get fielded in the forum. Questions and comments welcomed, but keep in mind that it is requested that the moderators keep this thread more well pruned than most.

[EDIT]Please note, this thread is intended to be a place for looking up the most common new programmer questions. If you can’t find any helpful information here, Please search using the vBulletin Advanced Search and SitePoint’s [URL=“http://search.sitepoint.com/”]Advanced Search. If you still can’t find anything, please start a new thread in the appropriate forum. Please do NOT ask questions in this thread.

  • Mittineague[/EDIT]

First - most basic of all - The PHP manual homepage for all languages, and [URL=“http://www.php.net/manual/en/”]The English Manual in particular. This covers everything though - so it can get intimidating fast.

That said, in your first six months or so with the language the section of that manual that you’ll spend the most time with is the base language reference. It and it’s table of contents are here.

Second most important thing to know is how to post your code examples. This is done using the highlight bb tags. The highlight tags can be told which language you are using.

Examples:

PHP

[noparse]


<?php
  // A simple hello world echo.
  echo 'Hello World';
?>

[/noparse]
creates…


<?php
  // A simple hello world echo.
  echo 'Hello World';
?>

Note that there are [noparse]


[/noparse] tags as well, but these have trouble with the \ character which will appear in examples involving namespaces, so the highlight tag is prefered.

Highlight can also do javascript, html, css and sql. If your example involves these consider posting in the forums set aside for them unless PHP is heavily involved with your question.

And now for the questions. If you have one that isn’t here then ask it.

Table of Contents:
[post=4753509]Coding Format Conventions[/post]

Moderators: If this thread catches on please stick - also please keep the Table of contents up to date.

Coding Formats

There are two major coding format styles which differ primarily in how braces are treated. Open, or emacs style


function foo( $var )
{
  switch( $var )
  {
    case 1:
      echo $var;
      break;
    case 2:
      echo $var;
      break;
    default:
      echo $var;
      break;
  }
}

And “inline” or “vi” style


function foo( $var ) {
  switch( $var ) {
    case 1:
      echo $var;
      break;
    case 2:
      echo $var;
      break;
    default:
      echo $var;
      break;
  }
}

Each style has adherents, and flame wars have erupted over them. The important part is to pick one and stick with it. When I was a beginner I used open style because I was learning from vbulletin code and that’s what vbulletin used in 3.x (what is used now I don’t know). I’ve since switched to closed for my own projects. It is important to be familiar with both since the use of a particular format may be a job requirement.

Both styles however do not allow for the following though the language itself does.


if ( $statement == true ) echo 'Hello';

if ($statement == false )
  echo 'false';

The saved keystrokes from not using braces here isn’t worth it the bugs that come up from misreading this.

From Template Engine to Language
How PHP’s heritage shapes its use.

Audience: Early Intermediate. This post presumes you understand basic syntax, control structures and the including and requiring of files.

PHP is a curious language. In what other programming language do you have to enclose all the code in tags? The answer is none - because PHP began as a template engine - specially a quick template run time for C++. Somewhere between the original PHP and PHP 3 it picked up so much functionality that people where able to start writing sites with it without touching C, and by version 4 the language picked up its first implementation of classes and began picking up the true trappings of a language.

And yet PHP still does some things like a template engine - and it’s important to understand this in order to avoid some weird bugs once you start trying to do more sophisticated things, particularly use the [fphp]header[/fphp] function.

First, PHP is an odd hybrid between an interpreted and compiled language. In a compiled language, like C++, C#, Java, and many others, a program called a compiler converts the code into instructions the machine can understand - either full on machine language like C++ does or bytecode for a virtual machine like Java. An interpreted language, like Javascript and older implementations of BASIC, transforms the code line by line.

PHP works file by file. It compiles the first file handed to it by the webserver, then does this process again whenever you call include or require (and the first time you call include_once or require_once for a given file).

Because of this certain errors - parse errors mostly - will occur before anything in the file gets done. Also PHP mercifully stops at the first parse error it encounters - Most C compilers for example do not and will happily report all other parse errors in the file - the problem with this is that the first error often is the cause for those that follows

Provided the code parses (the term compiles some times gets used but this implies a permanence PHP doesn’t have) the interpreter will start following instructions.

Here’s one of the first gotcha’s of PHP - anything and I do mean ANYTHING in the file outside the <?php ?> tags gets sent to output as soon the interpreter sees it. The problem with this is some functions - [fphp]header[/fphp] most prominent among them - cannot be called after this occurs and will error out.

Avoiding this is simple enough - make sure the file starts on <?php before anything else. You don’t have to have a closing ?> at the end of the file either if you don’t - but be consistent whichever approach you want to do.

Another piece of PHP’s heritage as a template engine is the presence of short tags. <? ?> and <?= ?> the “<?=” tag is equivalent to "<?php echo ". A third piece is PHP’s braceless syntax.

Ok, that’s all for now. Anyone got any questions or ideas for topics in this basics thread? One I will touch on later is the basics of errors.

Great thread!

I have a suggestion: a topic about connecting to the database and how to safely execute queries. Perhaps with a mysqli (procedural) and a PDO (OO) example?

Or maybe even a more basic explanation or tutorial involving working with arrays. Once you’ve worked with them for a while they become second nature, but I remember struggling with them during the first couple of days I was programming.

If you like, I could write up an explanation?

Procedural code can use classes without magically becoming “object oriented”, and there’s a bit more work to making a truly object oriented code base than just using the class keyword.

PDO would be a great next topic - but it’s something that will take me a few hours to type up - so maybe Sunday. It is important to start moving to PDO because the other access libraries may be moved out of PHP core to the PECL libraries soon (possibly starting with PHP 5.4) - meaning they won’t automatically be compiled in to the interpreter and code depending on them will be in danger of failing during major upgrades or server changes.

If you want to get arrays that would be wonderful! I didn’t make this thread to be the only instructor in it by any means. I want it to be a resource for new programmers and making it a good resource will take more time than I have.

EDIT: From an older thread posted by chris_fuel on Jun 26, 2006

The PHP website has the most friendly documentation system I’ve seen. If you know a function name, and simply want to look up syntax, you can use the following format:

http://www.php.net/[function_name]

for example, to look up the syntax for preg_match:

http://www.php.net/preg_match

This will give you the manual for preg match. If you’re only certain of a certain part (let’s say you know it’s preg something), you can enter that in as well:

http://www.php.net/preg

and you will be shown a list of functions that much. Each function page will give you 3 additional pieces of information. This includes:

  1. The category of the function, which starts with a ^ and is in a larger font (for example, preg_match is under the PCRE [Perl Compatible Regular Expressions] category)
  2. Additional functions/topics for that category, located underneat where #1 is
  3. Functions that provide similiar functionality, or used in conjunction with that particular function (fopen would point to frwite and fread, as they work together to deal with files).

Once you know the category, you can also enter it in the url to give you a general overview of functions/topics in that category:

www.php.net/pcre
www.php.net/mysql

Also don’t forget to read the user comments (and I mean all of them), as they will contain valuable gotchas and scripts that provide additional functionality. If you’re looking for a general topic, such as php security, you can simply go to php.net, select the dropdown list that says “functions” and choose “online documentation”, then enter your search item there.

thanks michael for the post, I know the post is old , but I am starting learning php now , my php learning journey starts from here.

Welcome to SitePoint a-flowers.

If you get stuck, just pop up a thread in the PHP Forum.

Enjoy your stay.

Anthony.

Could you please do that? still, I am very much scared of the arrays. :confused: I would love to see simple explanation or the tutorial link for the same. :slight_smile:

A little “feature” of PHP I’ve discovered is that the <?PHP token requires a space after it whereas after the <? and <% tokens a space is optional.

The error message you get if you miss the space is not too helpful so be warned!

(These examples only give a warning with error_reporting(E_ALL) )

<?PHP/<Some HTML>/?> fails…
<?/<Some HTML>/?> works…

Both of those optional tag openers are deprecated and their continued use is not advised. <?= is always on as of PHP 5.4, prior to that version short tags have to be turned on.

You are obviously right but now a days most of the developers facing a problem that their short tags generates an error on some servers, So for the better practices, i suggest developer to use <?php ?> tags instead of <? ?> or <?= ?> .

Keep in mind, <?= is not the same thing as <?. It isn’t considered a “short tag” but rather a shortcut for writing <?php echo

In my experience <?= is safe. Most modern PHP packages require mod_rewrite (or the equivalent) to be turned on, an it is impossible to block access to short tags and allow access to mod_rewrite. Also, PHP 5.4 supports it at all times. The true short tag, <? creates validation headaches with IDE’s.