Be a Supporter!

Php: Functions & Arrays (advanced)

  • 1,186 Views
  • 14 Replies
New Topic Respond to this Topic
different
different
  • Member since: Jul. 8, 2004
  • Offline.
Forum Stats
Member
Level 35
Blank Slate
Php: Functions & Arrays (advanced) 2007-04-19 15:20:42 Reply

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. :-)


> twitter.

DFox
DFox
  • Member since: Aug. 9, 2003
  • Offline.
Forum Stats
Member
Level 30
Blank Slate
Response to Php: Functions & Arrays (advanced) 2007-04-19 15:24:53 Reply

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!


BBS Signature
different
different
  • Member since: Jul. 8, 2004
  • Offline.
Forum Stats
Member
Level 35
Blank Slate
Response to Php: Functions & Arrays (advanced) 2007-04-19 15:27:14 Reply

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.


> twitter.

DFox
DFox
  • Member since: Aug. 9, 2003
  • Offline.
Forum Stats
Member
Level 30
Blank Slate
Response to Php: Functions & Arrays (advanced) 2007-04-19 15:29:52 Reply

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.


BBS Signature
Zendra
Zendra
  • Member since: Sep. 7, 2003
  • Offline.
Forum Stats
Member
Level 51
Blank Slate
Response to Php: Functions & Arrays (advanced) 2007-04-19 15:34:07 Reply

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.

different
different
  • Member since: Jul. 8, 2004
  • Offline.
Forum Stats
Member
Level 35
Blank Slate
Response to Php: Functions & Arrays (advanced) 2007-04-19 15:38:31 Reply

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!'


> twitter.

Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
Response to Php: Functions & Arrays (advanced) 2007-04-19 16:04:11 Reply

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

different
different
  • Member since: Jul. 8, 2004
  • Offline.
Forum Stats
Member
Level 35
Blank Slate
Response to Php: Functions & Arrays (advanced) 2007-04-19 17:37:07 Reply

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")


> twitter.

elbekko
elbekko
  • Member since: Jul. 23, 2004
  • Offline.
Forum Stats
Member
Level 16
Blank Slate
Response to Php: Functions & Arrays (advanced) 2007-04-19 18:01:03 Reply

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
DFox
DFox
  • Member since: Aug. 9, 2003
  • Offline.
Forum Stats
Member
Level 30
Blank Slate
Response to Php: Functions & Arrays (advanced) 2007-04-19 22:21:02 Reply

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 :)


BBS Signature
henke37
henke37
  • Member since: Sep. 10, 2004
  • Offline.
Forum Stats
Member
Level 30
Blank Slate
Response to Php: Functions & Arrays (advanced) 2007-04-20 02:57:53 Reply

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.

different
different
  • Member since: Jul. 8, 2004
  • Offline.
Forum Stats
Member
Level 35
Blank Slate
Response to Php: Functions & Arrays (advanced) 2007-04-20 03:21:21 Reply

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.


> twitter.

Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
Response to Php: Functions & Arrays (advanced) 2007-04-21 12:25:33 Reply

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'));

psicodemon
psicodemon
  • Member since: Aug. 1, 2004
  • Offline.
Forum Stats
Member
Level 28
Blank Slate
Response to Php: Functions & Arrays (advanced) 2010-08-15 06:51:17 Reply

Hello

I added little functionality to parse arrays in arrays. Not OOP though. If you want fast small lists with a few styling this is pretty cool.

<?php

function makeList($list, $type = false, $sub = false)
{
  /* Count all the items in the given array. -1 because array index starts at 0 */
  $itemCount = count($list) - 1;

  //if $type is not specified then the list will be an unordered list

  if ($sub)
    $html .= "\n<ol class=\"sub\">";
  else
    $html .= $type ? "\n<ol>" :  "\n<ul>";

  /* Why not foreach? Because I like to add <li class="first"> for styling */
  for($n = 0; $n <= $itemCount; $n++)
  {
    /* Check if there is an array inside the array (a sub-list) */
    if (is_array($list[$n]))
    {
      /* Recursive power, call this function again but force ordered list */
      $html .= makeList($list[$n], true, true);
    }
    else
    {
      /* If at start or at the end of the items add a class to the <li> */
      if ($n == 0)
        $html .= "\n<li class=\"first\">" .$list[$n]. "</li>";
      else if ($n == $itemCount)
        $html .= "\n<li class=\"last\">" .$list[$n]. "</li>";
      else
        $html .= "\n<li>" .$list[$n]. "</li>";
    }
  }

  /* Close the list or sub-list */
  if ($type)
    $html .= "\n</ol>";
  else
    $html .= "\n</ul>";

  return $html;
}

$myList = array("Example", "List", array("Test", "Sublist", "In a List", "Awesome!"), "Test", "Works", "Great!");

echo makeList($myList);

?>
psicodemon
psicodemon
  • Member since: Aug. 1, 2004
  • Offline.
Forum Stats
Member
Level 28
Blank Slate
Response to Php: Functions & Arrays (advanced) 2010-08-15 06:52:35 Reply

Also made one with crazy inline if-statements if you do not want a bulky function :)

<?php
function makeList($list, $type = false, $sub = false)
{
  $itemCount = count($list) - 1;
  $html .= $sub ? "\n<ol class=\"sub\">" : ($type ? "\n<ol>" : "\n<ul>");

  for($n = 0; $n <= $itemCount; $n++)
  {    
    $class = ($n == 0) ? "class=\"first\"" : (($n == $itemCount) ? "class=\"last\"" : "");
    $html .= (is_array($list[$n])) ? makeList($list[$n], true, true) : "\n<li $class>" .$list[$n]. "</li>";
  }

  $html .= $type ? "\n</ol>" : "\n</ul>";
  return $html;
}

$myList = array("Example", "List", array("Test", "Sublist", "In a List", "Awesome!"), "Test", "Works", "Great!");
echo makeList($myList);
?>

Fuck 80 char limit :P