phpRob 10 Posted November 2, 2011 Report Share Posted November 2, 2011 Having worked through the sort function example in Chapter 7 I noticed there's a call to print out the array 3 times using the same code. Could this be a case for a custom made function, or is there little point? If so how would the function look? I'm just curious as I've not yet touched functions in the book yet. Just thinking ahead This is my code: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Array - Sort</title> </head> <body> <div> <?php //Create array $team = array( 'Ba' => 9, 'Cabaye' => 4, 'Colocinni' => 2, 'Krul' => 1, 'Ben arfa' => 10, 'Jonas' => 18 ); //Print array before sort foreach ($team as $name => $number) { print "<p>$name, $number</p>"; } //Sort array by name ksort($team); ?> </div> <div> <?php //Print sorted array foreach ($team as $name => $number) { print "<p>$name, $number</p>"; } //Sort array by number asort($team); //Print sorted array foreach ($team as $name => $number) { print "<p>$name, $number</p>"; } ?> </div> </body> </html> Quote Link to post Share on other sites
Larry 433 Posted November 2, 2011 Report Share Posted November 2, 2011 Good thinking ahead. You could use a custom function here. I think it's a borderline case. But the function would be: function printArray($array) { foreach ($array as $name => $number) { print "<p>$name, $number</p>"; } } Quote Link to post Share on other sites
phpRob 10 Posted November 2, 2011 Author Report Share Posted November 2, 2011 Thanks Larry, just one question, why do you have to pass the argument ($array) within printArray? And would I call it in the script by typing - printArray($array); ? Quote Link to post Share on other sites
Larry 433 Posted November 2, 2011 Report Share Posted November 2, 2011 Sorry. I made a mistake in my code. I've fixed it, and you would call the function using: printArray($team); $team outside of the function gets its value passed to $array within the function. 1 Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.