PHP For the Road: Part 1
March 29th, 2008 | by Jez |I have decided to start a series on PHP Tips and Tricks, and I may even throw in a few other bits and bobs that I have come across. To start with, I’m going to be covering PHP shortcuts that every beginner should know (I didn’t find these out until much later in my PHP experience!) and a few other tidbits.
One of the more common tasks in PHP is printing an array item or variable out within a string of html. There are many ways of doing this, to see a full listing, visit php.net/string. I’m going to be focusing on a few shortcuts which don’t get mentioned very much and are often taken for granted.
The first method is using curly braces:
Alternatives to this would be to use string concatenation such as below:
However, this method does involve a whole extra 2 characters to type! but it provides memory benefits over parsing the variables directly in the string.
A quick way for just printing a variable in an HTML segment is to use the = operator after the php open tags followed by the variable and then close the tags again. For example:
-
<?
-
$foo = "Hello World";
-
?>
-
<h1><?=$foo?></h1>
-
<p>Lots of html text and declarations here</p>
Another alternative is using echo’s multiple parameters which is slightly faster than string concatenation. When passing parameters to echo a ‘,’ can be used to separate the variables and strings, and the echo function will display it as if it had been created any other way.
-
<?
-
$foo = "Hello";
-
$bar = "World";
-
//output: Hello, World
-
?>
As PHP has such a vast library of built in functions, you can never know if something exists for what you want, or if you have to make it yourself. I stumbled across a few which I never would have though existed.
This function basically retrieves an array of all of the meta tags within the included file. I came across this when looking into how to extract some custom meta data from a template system.
File_exists is a more common function, however its still valuable and can be overlooked if your creating a system demanding a lot of external resources.
If you have ever written such a large script that you cant remember what is declared where, a useful function is get_defined_vars. It will output all of the currently defined and accessible variables in a multi-dimensional array.
That’s it for Part 1, hopefully you have found something useful out of that, I’m hoping Part 2 might cover some more complex PHP ideas, if you have any requests please feel free to leave a comment!
Sorry, comments for this entry are closed at this time.