vujsa 0 Report post Posted March 20, 2007 Well, it has been a while since I offered a tutorial here at Xisto. 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: <?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: <?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$seperatorAs a result, our function would start like so: function list_sort($input, $sort_order, $sort_type, $seperator) Now to use the original code as the base for out function: <?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: split foreach trim sort rsort implode switchI hope that this tutorial will offer new users of PHP a valuable example of how to use PHP and write functions. vujsa Share this post Link to post Share on other sites
Quatrux 4 Report post Posted March 21, 2007 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 Share this post Link to post Share on other sites
delivi 0 Report post Posted March 21, 2007 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. Share this post Link to post Share on other sites
vujsa 0 Report post Posted March 31, 2007 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. <?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! <?phpfunction 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 = 30 This 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. [/hr] 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! <?phpecho "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: . $2.00 $13.00 + $5.00 ---------- $20.00 (5%) $1.00 ---------- $21.00Having 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 Share this post Link to post Share on other sites
Chesso 0 Report post Posted March 31, 2007 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. Share this post Link to post Share on other sites
TavoxPeru 0 Report post Posted April 7, 2007 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, Share this post Link to post Share on other sites
iGuest 3 Report post Posted April 8, 2007 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: 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: <?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 Share this post Link to post Share on other sites