Forum Topic: Php: Functions & Arrays (advanced)

(466 views • 12 replies)

This topic is 1 page long.

<< < > >>
None

different

Reply To Post Reply & Quote

Posted at: 4/19/07 03:20 PM

different DARK LEVEL 35

Sign-Up: 07/08/04

Posts: 3,764

PHP: Main - It's like triple chocolate icecream

------------------------

This is an extension to Momo's tutorial which is also listed in PHP Main. We're going to be focusing on user defined functions, arguments etc. You should have a basic understanding of PHP at least - this tutorial is not for newbies.

So we're going to start off with a simple array of fruits:

<?php
$fruit = array("Banana", "Kiwi", "Melon", "Orange", "Pear", "Strawberry");
print_r($fruit);
?>

So I just chose some random fruits, obviously then printing the output. Now, to DO anything with this kind of output I can use a foreach() loop OR a for() loop. Let's do both.

<?php
// add in the code from the previous block, drop the print_r if you like
foreach ($fruit as $f)
{
echo "I like $f very much. <br />";
}
//foreach loop will go through all the array elements, so you should have an output for all your array keys
?>

So there you can see that PHP will run through every single array key performing what's in the curly brackets. for() loops are more complicated but more flexible. Let's say we just wanted to do the first 3 keys of the array:

<?php
for ($i=0;$i<3;$i++)
{
echo "Only the first three keys. This one just happens to be $fruit[$i]<br />";
}
?>

By substituting the number inside the square brackets, we use the increment $i on the array. Of course we can emulate the foreach loop by changing the first line to:

for ($i=0;$i<count($fruit);$i++)

Functions

Functions are pretty straightforward. You define a function like this:

function myFunction()
{
//sample code goes here
}

Optional arguments can be defined within the brackets. For example, say I wanted to add in a string to another string:

<?php
function ins_String($str1, $str2)
{
//use two arguments - one for the first string, other for the second
echo $str1 . " " . $str2;
}

ins_String("Hello", "World");
?>

Simple.

Now, how about functions and arrays? Well, let me show an example I did a while ago for generating lists. My final goal was to create a function that would let me do a HTML list with the type of list as an optional argument.

Our result wants to be like this:

<ul>
<li>This</li>
<li>Is</li>
<li>Example!</li>
</ul>

I didn't want to do sublists at the time, but it could probably be done just as easily. Now, our function needs to be expanded/shrunk on the fly, so we're going to use an array as an input.

$myList = array("Example", "List", "Test", "Works", "Great!");

So now the function:

function htmList($array, $type="u") {
//Here I am setting a default value for type - so if it is not specified then the list will be an unordered list
$items = count($array);
//Count the number of items in the list
if ((!$type == "u") OR (!$type=="o")) { $type = "u"; }
// Checks for what value type is. If it's not unordered or ordered then default to unordered.
echo "<{$type}l>";
// Prints the html for the list type
for($i=0;$i<$items;$i++)
{
echo "<li>" . $array[$i] . "</li>";
// Loop through all the elements and generate a list item for each
}

echo "</{$type}l>";
//Finally validate our list! Note the curly brackets so as to show PHP that $typel is not a variable
}

And then generate the list with:

htmList($myList, "o");

Or:

htmList($myList);

Hope you learned something. :-)

we play iPhone, daily game reviews, twitter.


None

DFox

Reply To Post Reply & Quote

Posted at: 4/19/07 03:24 PM

DFox LIGHT LEVEL 30

Sign-Up: 08/09/03

Posts: 9,467

Very cool tutorial.

I liked it because you touched on a lot of useful/interesting aspects.

The one critique I have right now is that I wouldn't name a parameter "$array", but it's not that terrible.

Anyway, very nice job!


None

different

Reply To Post Reply & Quote

Posted at: 4/19/07 03:27 PM

different DARK LEVEL 35

Sign-Up: 07/08/04

Posts: 3,764

At 4/19/07 03:24 PM, DFox wrote: The one critique I have right now is that I wouldn't name a parameter "$array", but it's not that terrible.

Ah well, if it's a reserved word then I wouldn't have used it. But the script ran fine on my PHP server - obviously the parameter could have any name you chose there! Even $igloo. If you really wanted it to be called $igloo.

we play iPhone, daily game reviews, twitter.


None

DFox

Reply To Post Reply & Quote

Posted at: 4/19/07 03:29 PM

DFox LIGHT LEVEL 30

Sign-Up: 08/09/03

Posts: 9,467

At 4/19/07 03:27 PM, different wrote: Ah well, if it's a reserved word then I wouldn't have used it. But the script ran fine on my PHP server - obviously the parameter could have any name you chose there! Even $igloo. If you really wanted it to be called $igloo.

Yeah I know, I'm just not a huge fan of it. If you're using multiple arrays in the function $array might get confusing.

But it all comes down to personal preference I guess, but I learned never to name variables or arrays solely on their data type.


None

Zendra

Reply To Post Reply & Quote

Posted at: 4/19/07 03:34 PM

Zendra NEUTRAL LEVEL 41

Sign-Up: 09/07/03

Posts: 12,470

Overall it's a great tutorial! :)

At 4/19/07 03:29 PM, DFox wrote: Yeah I know, I'm just not a huge fan of it. If you're using multiple arrays in the function $array might get confusing.

But when programming it's most likely people will give it a name similar to the data it will store. Such as when it will store user data, it would be (logically) called $userData, or whatever. So, it's not a big problem, for an example it should work well.

NG BBS & Review moderator // PM abuse // Check my audio!


None

different

Reply To Post Reply & Quote

Posted at: 4/19/07 03:38 PM

different DARK LEVEL 35

Sign-Up: 07/08/04

Posts: 3,764

At 4/19/07 03:29 PM, DFox wrote:
Yeah I know, I'm just not a huge fan of it. If you're using multiple arrays in the function $array might get confusing.

This function isn't designed for multiple arrays... ;-)

At 4/19/07 03:34 PM, Zendra wrote:
But when programming it's most likely people will give it a name similar to the data it will store. Such as when it will store user data, it would be (logically) called $userData, or whatever. So, it's not a big problem, for an example it should work well.

Exactly - it's like if I'm going to be storing fruits in an array, I don't tend to call them record shops. I call them fruits!

It's personal preference and at the end of the day, using $array as an example is more helpful - as people are going to think 'well, an array goes there!'

we play iPhone, daily game reviews, twitter.


None

Pilot-Doofy

Reply To Post Reply & Quote

Posted at: 4/19/07 04:04 PM

Pilot-Doofy NEUTRAL LEVEL 37

Sign-Up: 09/13/03

Posts: 12,275

I'm still disappointed to not see anything on multidimensional arrays. :(


None

different

Reply To Post Reply & Quote

Posted at: 4/19/07 05:37 PM

different DARK LEVEL 35

Sign-Up: 07/08/04

Posts: 3,764

At 4/19/07 04:04 PM, Pilot-Doofy wrote: I'm still disappointed to not see anything on multidimensional arrays. :(

Arrays made up of arrays?

$bears = array("Brown", "Black");
$fish = array("Clown", "Sword");
$animals = array($bears, $fish);

Or associative arrays?

$green = array("recycled paper"=>"less cutting down of trees", "hydrogen powered cars"=>"less carbon monoxide / carbon dioxide released into atmosphere")

we play iPhone, daily game reviews, twitter.


None

elbekko

Reply To Post Reply & Quote

Posted at: 4/19/07 06:01 PM

elbekko EVIL LEVEL 16

Sign-Up: 07/23/04

Posts: 6,587

The first. But both should be covered.

"My software never has bugs. It just develops random features. " - Unknown

[ FluxBB developer | Quickmarks 0.5.1 | Strings & Ints - my blog ]

BBS Signature

None

DFox

Reply To Post Reply & Quote

Posted at: 4/19/07 10:21 PM

DFox LIGHT LEVEL 30

Sign-Up: 08/09/03

Posts: 9,467

Oh yeah, different, please post this in PHP: Main because there's no way I'll remember to include it otherwise when the update comes along :)


None

henke37

Reply To Post Reply & Quote

Posted at: 4/20/07 02:57 AM

henke37 NEUTRAL LEVEL 23

Sign-Up: 09/10/04

Posts: 3,552

I want to mention that you completlly omitted the foreach construct.

Each time someone abuses hittest, God kills a kitten. Please, learn real collision testing.


None

different

Reply To Post Reply & Quote

Posted at: 4/20/07 03:21 AM

different DARK LEVEL 35

Sign-Up: 07/08/04

Posts: 3,764

At 4/20/07 02:57 AM, henke37 wrote: I want to mention that you completlly omitted the foreach construct.

I want to mention that you completely didn't read through the topic properly.

we play iPhone, daily game reviews, twitter.


None

Pilot-Doofy

Reply To Post Reply & Quote

Posted at: 4/21/07 12:25 PM

Pilot-Doofy NEUTRAL LEVEL 37

Sign-Up: 09/13/03

Posts: 12,275

At 4/19/07 05:37 PM, different wrote:
At 4/19/07 04:04 PM, Pilot-Doofy wrote: I'm still disappointed to not see anything on multidimensional arrays. :(
Arrays made up of arrays?

Yes, hence, they are made up of several dimensions.

$myArray = array('Value #1', array('Value #2', 'Value #3'));


All times are Eastern Standard Time (GMT -5) | Current Time: 04:58 AM

<< Back

This topic is 1 page long.

<< < > >>
You need a Grounds Gold Account to post on the NG BBS! If you don't have one, click here to sign up now! It's fast, free, and easy — and opens up tons of great NG features!