vujsa
Mar 20 2007, 09:04 PM
Well, it has been a while since I offered a tutorial here at AstaHost. Most of my creativity has gone toward my new website, Handy PHP. The website is just getting started and it is hard to post potential content for my website here instead of there. The purpose of this tutorial is to show you how to convert a standard PHP script into a reusable PHP function. It is funny, because this tutorial is very similar in nature to the very first tutorial I wrote here. Rapid HTML code generation using simple PHP would be a good topic to read with this tutorial. Before we start, I'll try to explain the benefits of using a function instead of regular code for your scripts. Functions consolidate several lines of code into a single entity that can be requested over and over again. Imagine that your function is an art box and that your art box contains everything you need to draw a picture. You know that any time you want to draw a picture, you simply need to use your art box! If you do not have an art box, every time you want to draw a picture, you have to go find each of the needed items before you can start to draw! Imagine that you have the following script: CODE <?php // First our input string: $a = "train, car, horse, mule, truck, plane, trolly, bus";
// Convert our input string into an array: $b = split(',', $a);
// Next we need to remove any extra whitespace from our value to ensure proper sorting: $i = 0; foreach ($b as $c) { $b[$i] = trim($c); $i++; }
// Now we sort our values in alphabetical order: sort($b, SORT_STRING);
// We now convert our array back to a string: $c = implode(", ", $b);
// Finally, we output the results: echo "<pre>\n"; echo "Input: \"" . $a . "\"\n"; echo "Output: \"" . $c . "\"\n"; echo "</pre>\n"; ?>
Would output: Input: "train, car, horse, mule, truck, plane, trolly, bus" Output: "bus, car, horse, mule, plane, train, trolly, truck" While this script is not very long, it could become tiredsome to have to copy it every time we want to sort some values. Imagine that we have several strings of values we want to sort in various ways: CODE <?php
// SORT THE VEHICLES WE COMMONLY USE ALPHABETICALLY!!!!!!!!! // First our input string: $a1 = "train, car, horse, mule, truck, plane, trolly, bus";
// Convert our input string into an array: $b1 = split(',', $a1);
// Next we need to remove any extra whitespace from our value to ensure proper sorting: $i1 = 0; foreach ($b1 as $c1) { $b1[$i1] = trim($c1); $i1++; }
// Now we sort our values in alphabetical order: sort($b1, SORT_STRING);
// We now convert our array back to a string: $c1 = implode(", ", $b1);
// Finally, we output the results: echo "<pre>\n"; echo "Input: \"" . $a1 . "\"\n"; echo "Output: \"" . $c1 . "\"\n"; echo "</pre>\n";
// SORT OUR AGED NUMERICALLY IN REVERSE
// First our input string: $a2 = "32,25,65,85,45,15,75,35,24,26,46,29";
// Convert our input string into an array: $b2 = split(',', $a2);
// Next we need to remove any extra whitespace from our value to ensure proper sorting: $i2 = 0; foreach ($b2 as $c2) { $b2[$i2] = trim($c2); $i2++; }
// Now we sort our values in alphabetical order: rsort($b2, SORT_NUMERIC);
// We now convert our array back to a string: $c2 = implode(",", $b2);
// Finally, we output the results: echo "<pre>\n"; echo "Input: \"" . $a2 . "\"\n"; echo "Output: \"" . $c2 . "\"\n"; echo "</pre>\n";
// SORT OUR FRUITS ALPHBETICALLY IN REVERSE
// First our input string: $a3 = "peach, pear, orange, apple, grape, kiwi, cherry, lemon, watermelon, lime";
// Convert our input string into an array: $b3 = split(',', $a3);
// Next we need to remove any extra whitespace from our value to ensure proper sorting: $i3 = 0; foreach ($b3 as $c3) { $b3[$i3] = trim($c3); $i3++; }
// Now we sort our values in alphabetical order: rsort($b3, SORT_STRING);
// We now convert our array back to a string: $c3 = implode(", ", $b3);
// Finally, we output the results: echo "<pre>\n"; echo "Input: \"" . $a3 . "\"\n"; echo "Output: \"" . $c3 . "\"\n"; echo "</pre>\n"; ?>
Would output: Input: "train, car, horse, mule, truck, plane, trolly, bus" Output: "bus, car, horse, mule, plane, train, trolly, truck"
Input: "32,25,65,85,45,15,75,35,24,26,46,29" Output: "85,75,65,46,45,35,32,29,26,25,24,15"
Input: "peach, pear, orange, apple, grape, kiwi, cherry, lemon, watermelon, lime" Output: "watermellon, pear, peach, orange, lime, lemon, kiwi, grape, cherry, apple" As you can see, the code has gotten much larger and we are just doing the same thing over and over again. What if we had 100 lists to sort? That would be a very large script wouldn't? In order to create a function to replace all of this code, we first have to find the differences between each of the sections of code. - The very first difference is the $a variable ($a1, $a2, $a3).
- The input value is different in each case. - The next difference is the sort method: (sort($b1, SORT_STRING), rsort($b2, SORT_NUMERIC), rsort($b3, SORT_STRING)).
- Either sort normally or in reverse with sort or rsort. - Either sort numerically or alphabetically with SORT_NUMERIC or SORT_STRING - And the final difference is the implode method:(implode(", ", $b1), implode(",", $b2), implode(", ", $b3)).
- Either add a comma between each item or a comma and a space between each item.
These differences will be our function arguments. We will name our function list_sort(). Our function arguments would be as follows: - $input
- $sort_order
- $sort_type
- $seperator
As a result, our function would start like so: CODE function list_sort($input, $sort_order, $sort_type, $seperator) Now to use the original code as the base for out function: CODE <?php function list_sort($input, $sort_order, $sort_type, $seperator){
// First our input string: $a = $input;
// Convert our input string into an array: $b = split(',', $a);
// Next we need to remove any extra whitespace from our value to ensure proper sorting: $i = 0; foreach ($b as $c) { $b[$i] = trim($c); $i++; }
// Select the correct sort method using a switch: switch($sort_order){ case 'normal': sort($b, $sort_type); break; case 'reverse': rsort($b, $sort_type); break; default: sort($b, $sort_type); break; }
// We now convert our array back to a string: $c = implode($seperator, $b); return $c; } $a1 = "train, car, horse, mule, truck, plane, trolly, bus"; $a2 = "32,25,65,85,45,15,75,35,24,26,46,29"; $a3 = "peach, pear, orange, apple, grape, kiwi, cherry, lemon, watermelon, lime";
// Finally, we output the results: echo "<pre>\n"; echo "Input: \"" . $a1 . "\"\n"; echo "Output: \"" . list_sort($a1, 'normal', SORT_STRING, ', ') . "\"\n"; echo "</pre>\n";
echo "<pre>\n"; echo "Input: \"" . $a2 . "\"\n"; echo "Output: \"" . list_sort($a2, 'reverse', SORT_NUMERIC, ',') . "\"\n"; echo "</pre>\n";
echo "<pre>\n"; echo "Input: \"" . $a3 . "\"\n"; echo "Output: \"" . list_sort($a3, 'reverse', SORT_STRING, ', ') . "\"\n"; echo "</pre>\n"; ?>
Would output: Input: "train, car, horse, mule, truck, plane, trolly, bus" Output: "bus, car, horse, mule, plane, train, trolly, truck"
Input: "32,25,65,85,45,15,75,35,24,26,46,29" Output: "85,75,65,46,45,35,32,29,26,25,24,15"
Input: "peach, pear, orange, apple, grape, kiwi, cherry, lemon, watermelon, lime" Output: "watermellon, pear, peach, orange, lime, lemon, kiwi, grape, cherry, apple" As you can see, we haven't added very much code but have managed to replace the script with a function. There a several areas of this example that provide for improvement opportunities. Can you find them? I'll give you one hint, how often do we use a string seperator in this function? While my previous tutorial related to functions dealt with using a function to build HTML, this example shows a more basic use for a function and how functions can make programming easier. I look forward to the opportunity to further discuss this as well as much more advanced functions as there is a great deal of information that hasn't been talked about here yet. This includes using function calls, default argument values for functions, and error checking. For more information, please check out these areas: I hope that this tutorial will offer new users of PHP a valuable example of how to use PHP and write functions. vujsa
Reply
Quatrux
Mar 21 2007, 05:31 AM
Nice tutorial, it is very clear, well for me at least, but when reading it I think it is clear for a newbie or novice php programmer too. I could suggest to later in another of your tutorials to add some information, that you can use your own defined constants in the functions and don't need to pass them into the functions, also about the global $var; command or any other, static and similar, due to people usually drop functions they can't use something from outside, even though it is possible and is quite easy. Nice job
Reply
livingston
Mar 21 2007, 06:44 PM
this is one of the best tutorials that I've come across. The tutorial is clear and easy to understand. I'll definitely try this and thanks very much for sharing this.
Reply
vujsa
Mar 31 2007, 06:42 AM
QUOTE(Quatrux @ Mar 21 2007, 12:31 AM)  Nice tutorial, it is very clear, well for me at least, but when reading it I think it is clear for a newbie or novice php programmer too. I could suggest to later in another of your tutorials to add some information, that you can use your own defined constants in the functions and don't need to pass them into the functions, also about the global $var; command or any other, static and similar, due to people usually drop functions they can't use something from outside, even though it is possible and is quite easy. Nice job  Well, it is true that you can't simply use any variable in your script inside of your function without a little preperation. Here is why. Think of it as having 2 different variable scopes. Global and local scopes. That is a loacl variable won't work in the global environment and a global variable won't work in the local environment. Your script is the global scope and your function is the local scope. Additionally, a local variable will only work in it's local scope, it won't work in a different local scope. Basically, a variable in function "A" won't work in function "B" or anywhere else in the script outside of that function. In order to use a variable from the global scope in a function, you have to specify that the variable used is global. CODE <?php $a = 5; $z = 13;
function difference(){ global $a, $z; $z = $z - $a; }
difference(); echo $z; ?> This would output 8 since the function had access to both $a and $z. Since the function had access to these variables, it was able to manipulate those variables. If a variable isn't asigned prior to declaring it as a global variable in a function, the variable will still work once the function is called! CODE <?php function show_global(){ global $a, $b; $a = 20; $b = 30; }
echo "Before Function:<br>\n"; echo "A = $a <br>\n"; echo "B = $b <br>\n<br>\n";
show_global();
echo "After Function:<br>\n"; echo "A = $a <br>\n"; echo "B = $b <br>\n<br>\n"; ?> Will show the following: Before Function: A = B =
After Function: A = 20 B = 30This is because the as far as the script was concerned, the variables were not assigned prior to the function being called. So not only does "global" allow a function to use a global scope variable, it also allow the script to use a function assigned in a function. In addition to being able to use your variables at will in your functions, you can also use functions in functions. In the first post, you saw me use predefined functions like sort(), split(), and implode() in the function I created called list_sort()! You can use functions that you create in your other functions as well. In fact, you can create several small functions like pieces of a puzzle and then use one larger function to put all of the pieces together for you! Another thing to keep in mind is that it doesn't matter what order you create the functions in. As long as every function called is defined somewhere in your script, it will work. And a function can be called before it is defined! CODE <?php echo "Before Function:<br>\n"; echo "A = $a <br>\n"; echo "B = $b <br>\n<br>\n";
show_global();
echo "After Function:<br>\n"; echo "A = $a <br>\n"; echo "B = $b <br>\n<br>\n";
function show_global(){ global $a, $b; $a = 20; $b = 30; }
?> The above script will display the exact same output as the one before even though the function is defined after the call! Many people get used to the idea that the parser executes line 1, line 2, line 3 etc... and it does. As a result, you have to assign a variable on a line before the line that tries to use it. A function does not have to be defined on a line preceeding the line that uses it. Again, think of the functions like pieces of a puzzle. the pieces are disorganized and out of place and it is the rest of the code that puts those pieces in order. If the functions are the pieces, then the script is the person working the puzzle. You start with the border then match the pieces together for the corect fit. That is what the script does. The script arranges the functions so that they build the complete picture. Using functions in this way is the first step to Object Oriented Programming. While this discussion could very easily go on to Objects and Classes, it should remain concentrated on the creation of user defined functions. I will attempt to discuss error checking and handling in your new functions when I am able to add to this topic. Until then, write some functions. Don't understand something, look it up or just give it a try and see if the output can show you what the function is doing. If the function works, was it what you expected? Try writing a function that will calculate sales tax for you: CODE . $2.00 $13.00 + $5.00 ---------- $20.00 (5%) $1.00 ---------- $21.00 Having a goal in mind usually helps me work through a script. Also, working on small sections of scripts or functions helps me break a large project into several small projects. For example, how do we get the dollar amounts used for addition? Pehapes a function just to gather all of the values and aadd then together would be a good place to start! Please don't post the solution here as it would only spoil the exercise for future readers. vujsa
Reply
Chesso
Mar 31 2007, 03:01 PM
vujsa sorry to cut in here, but do you have any advice for tutorial layout (and like what is good to build for creation)? My site has somewhat a simple and good enough file layout, just basic tables with minimal information, description and screenshot, but I have never gotten the tutorial aspect off the ground because it's rather annoying to write for and have it displayed nicely.
Reply
TavoxPeru
Apr 7 2007, 03:50 AM
Thanks for this nice tutorial, after read the post some good ideas came across so i will start reviewing some of my code. Best regards,
Reply
mastercomputers
Apr 8 2007, 02:37 AM
Hey vujsa, I like the new look of HandyPHP.com, much better than what it was before. When designing functions, try to think of what purpose you want to use it for. Most functions I create are to eliminate the need to keep reusing the same piece of code over and over again, the less code we have the easier it is for us to maintain (so to speak), however it can get messy when we're jumping all over the place from function to function, in which you might be better off with enclosing it all inside it's own object (class), in which everything about that object is stored within itself which makes it even easier on us because we don't have to step through each piece of our code when we know it's all contained at one easy to navigate section. I notice that for vujsa, he's designing a function based on a script he already has in place, which should work as he's got it (haven't checked). What I do first is ensure that the code is simple and as clean as possible, so it's even easier to work with, I try to see areas that are just extra work when it could be eliminated sooner. So I'm just going to go over his code first, and look at areas we can clean up. He uses a comma separated string value as the input, the data we want to work with. Now, obviously he knows how this data comes about, and whether it would maintain this format or not, if you understand how your data is gotten, then you know exactly what you should be working with. He wants to turn it into an array using split, first of all, this is overkill if you know how your data is formatted. split() uses regular expression patterns which means a regular expression engine will be used to process this inbuilt function. We really should be using explode(). Next I see white spaces being removed by looping through an array, well if we had done: CODE explode(', ', $a); We shouldn't have to worry about removing white spaces, again this depends on how the data is formatted. Everything else afterwards is quite fine yet needs to show you understand the code you're using, also there's the overuse of echo, should always limit the amount of times you call it, if possible try to cut it down. Also try to use the correct quotes (single and double). So here's a cleaned up version: CODE <?php $input = 'bus, car, boat, caravan, jet fighter, horse, ox, skateboard, bicycle, motorbike'; $vehicles = explode(', ', $input); sort($vehicles); $output = implode(', ', $vehicles); echo '<p>Input: ' . $input . '</p><p>Output: ' . $output . '</p>'; ?> Now if we to create a function for this, it's basic principle is to take our input and output it sorted. We could add additional parameters to the script for different outputs, but keep to the basics. You may have been thrown in the deep end, because you need to understand functions, and which one would be correct for your needs. Look at the cleaned up version, I use explode() and store it inside a variable, however I use sort() and have not assigned it a variable, now why is that? The reason is, the results that these functions return, or what these functions actually do is completely different. explode() returns an array, which is why I assign it to $vehicles, sort() returns a boolean value to suggest whether the function worked or not, so assigning the sort to a variable will only allow me to check whether the function actually worked but how is it useful and how does it sort? Well the thing with sort is, it takes the actual reference of the array you're passing it, meaning it will alter the array you pass to it, so basically it's altering $vehicles itself. I may have lost you here because I haven't explained it clearly but you should research into functions and try to understand the types of returns that you can do, so you can make effective and useful functions. So how would I code a function to sort my string? I'm not going to say, I think vujsa has provided enough information to at least create something basic to do just that, but remember, try to not do too many things at once, keep it simple. Cheers, MC
Reply
Similar Topics
Keywords : writing functions php php script reusable php function- Preventing Spam When Using Php's Mail Function
- (6)
First of all, if this is not the correct place for this topic please an Admin move it accordingly.
Recently i read at the PHPBuilder.com website this excelent article Preventing spam when using
PHP's mail function that explains in a very easy way how to avoid spammers send their spam from
your own server. Generally speaking, almost all websites includes some kind of contact form which
is used to send emails with the php mail() function, this contact form can be used for a lot of
purposes like for example to send comments or sugestions, to report problems on you...
PHP: Writing A Generic Login And Register Script
- (14)
Now there are basically 3 functions that a user management system provides: login, register, and
protection. A user management system can do more than this but that is all that this tutorial will
be covering. I will try to explain what I am doing as I go along but to fully understand what is
happening you should have a basic knowledge of PHP, SQL, and HTML. This tutorial assumes you are
using MySQL, adjust accordingly for a different DBMS. First off lets define the database table
where our users will be stored. Using phpMyAdmin run this statement to create our table...
Php: Lesson #3;functions
- PHP. (0)
A Simple Register Script
- This Is a Very Simple Register-Script (3)
Some time ago, i made a login-script. But how do you use a login-script, if you can't register.
So this morning, I decided to make a register-script.. What you should already know: The php
basics and a little more. How to use php and mysql together. The HTML basics (to make the forms).
The first thing we should do, is creating the database tables. Here is the code: CODE CREATE
TABLE `user` ( `id` int(4) unsigned NOT NULL auto_increment,
`username` varchar(32) NOT NULL, `password` varchar(32)...
PHP Tutorial: Form Verification And Simple Validation
- A One Page script for PHP form verification. (12)
Having used various means of verifying HTML forms I believe that this method of verifying a form
to be the best mostly because it does everything on one page. It presents the form on one page and
then when the submit button is pressed, if all the required fields are not filled out then it will
present the form again with all the fields intact and in red lettering will point out the fields
that are required to be filled out in red. It is not possible to click submit using this method even
if the user has turned JavaScript off. While it is possible to use javascript to ...
Creating A Php Login Script
- A thorough look at the process behind it (3)
Hey all, after reading through a fair number of tutorials on this subject I decided to write a
pretty detailed one myself. Apologies for those who don't like my structured layout, it's
just the way I do things. /wink.gif" style="vertical-align:middle" emoid=";)" border="0"
alt="wink.gif" /> Title: Creating a PHP Login Script Objective: To go through a series of basic
steps required to create a method of user registration, login and permission management using PHP
and MySQL. Notes: The information is designed to work fully on AstaHost's hosting plans. ...
Very Simple Login-script
- This is a very simple and secure login-script (18)
Hi. This is my first post here. please Tell me if i do something wrong. This is a very simple and
secure login script. I will try to add as many comments as possible, to make it easier to
understand. Lets start with the database. Just make a new SQL file, and call it whatever you want.
Paste this code: CODE CREATE TABLE `user` ( `id` int(4) unsigned
NOT NULL auto_increment, `username` varchar(32) NOT NULL, `password`
varchar(32) NOT NULL, `level` int(4) default '1', PRIM...
Attack Script In Php
- This is a funny attack script that i made (5)
Hey! I am going to share an attack script that i made for some time ago. I made it, as a test
for my game.. And ofc, you can use it for your game to. It is still version 1.0. But I want you to
learn something from it /wink.gif" style="vertical-align:middle" emoid=";)" border="0"
alt="wink.gif" /> This is my second tutorial here, and I will try to make it better than my first
one /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /> Here is
the SQL File. CODE CREATE TABLE `characterss` ( `health` int(2...
Calendar And The Date () Function
- Making Math Simple With Modular Arithmetic (0)
In my days of calendar making I've encountered a few minor inconveniences. When you try to make
a calendar, you have to find a few specific things: (1) the first day of the month, (2) how many
days are in the month, and (3) what today's date is. The second and third ones are easy to find.
Before we start making a calendar, though, let's set some ground rules: CODE define
('TS', time ()); Now we can find (2) and (3) from above: CODE
$total_days = (int) date ('t', TS); $todays_date = (i...
Simple User Validation Script
- (5)
This tutorial will show you how to create a simple user validation script with PHP. We will need
two files: "protect.php" and "login.php". The protect file is not meant to be viewed by itself. In
order to protect a page, you need to include that file by using PHP code like the following: CODE
include("protect.php"); Keep in mind that this needs to be in between your
tags. This bit of code uses the include function. It is a handy function that reads all the
information contained in one file and temporarily adds it to another. For example, this c...
Creating Your Own Image Gallery With Php
- A Guideline, Not A Complete Script (3)
Recently a member asked how to create a photo gallery using his various directories filled with
image files. Here is an overview of the steps and fuctions needed to do this. Assuming that the
following directories exists and are full of image files: www.testsite.web/photos/gallery1/
www.testsite.web/photos/gallery2/ www.testsite.web/pictures/album1/ In order to get the contents
for a specific gallery you'll need to let the script know which one to look in. You'll need
to use a link that carries the arguments needed to locate the right photos. www.testsite.we...
Sending Authorised Mail Using Imap_mail Function
- Mailing through imap_mail(). (2)
hi, if you have an IMAP account then you can send the mail using the imap_mail() function of php.
it is similar to mail() function but is an authorative way.. because your email account will require
authorisation while sending an email here goes an example.. ==================================
imap_mail (PHP 3>= 3.0.14, PHP 4 , PHP 5) imap_mail -- Send an email message Description bool
imap_mail ( string to, string subject, string message ]]] ) This function allows sending of
emails with correct handling of Cc and Bcc receivers. Returns TRUE on success or FAL...
PHP Tutorial: Menu Or Sidebar Script For CMS101
- and other applications as well (6)
A Php Menu-builder Tutorial This Sidebar Menu-builder code and the php scripts are adapted from
a Tutorial on the Astahost.com Forum titled : CMS101 - Content Management System Design .
Since the original tutorial's author (vujsa) did such a marvellous job of describing the system
in the original Topic posting, I will not attempt to explain it here, rather, I invite you to have a
look at his Topic and learn from it. The Basic tutorial provided coding for developing a table-based
web-site template which used php includes and embedded data to create a &...
Sending Mail Using PHP's Mail() Function
- Send mail from any account 2 any account (2)
hi, It is possible to send mail from any account to any account using the php's built in
mail() function.. for which is very easy to write the coding... wt you are supposed to do is just
pass the parameters like from, to, subject, message .. and attachments if any, and your email will
be sent in no time.. as Astahost.com supports the php scripts you can use it if you already have
an account here... ============================================== Example 1. Sending mail.
mail("joecool@example.com", "My Subject", "Line 1\nLine 2\nLine 3"); ?> ...
Looking for writing, functions, php
|
*RANDOM STUFF*
*SIMILAR VIDEOS*
Searching Video's for writing, functions, php
|
advertisement
|
|