Jump to content
Larry Ullman's Book Forums

Custom Functions


Recommended Posts

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

 

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

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

 Share

×
×
  • Create New...