Jump to content
Larry Ullman's Book Forums

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 post
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 post
Share on other sites

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...