phpRob Posted November 2, 2011 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> Link to comment Share on other sites More sharing options...
Larry Posted November 2, 2011 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>"; } } Link to comment Share on other sites More sharing options...
phpRob Posted November 2, 2011 Author 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); ? Link to comment Share on other sites More sharing options...
Larry Posted November 2, 2011 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 Link to comment Share on other sites More sharing options...
Recommended Posts