100% found this document useful (1 vote)
42 views

PHP 5 Advanced Visual QuickPro Guide 2nd Edition Larry Ullman pdf download

The document is a promotional listing for various PHP-related ebooks, including 'PHP 5 Advanced Visual QuickPro Guide' by Larry Ullman. It provides links to download these ebooks in multiple formats and includes a table of contents for the 'PHP 5 Advanced' guide, detailing chapters on advanced techniques, web application development, database concepts, security, e-commerce, and more. The document also contains publisher information and copyright details.

Uploaded by

zagiaferb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
42 views

PHP 5 Advanced Visual QuickPro Guide 2nd Edition Larry Ullman pdf download

The document is a promotional listing for various PHP-related ebooks, including 'PHP 5 Advanced Visual QuickPro Guide' by Larry Ullman. It provides links to download these ebooks in multiple formats and includes a table of contents for the 'PHP 5 Advanced' guide, detailing chapters on advanced techniques, web application development, database concepts, security, e-commerce, and more. The document also contains publisher information and copyright details.

Uploaded by

zagiaferb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

PHP 5 Advanced Visual QuickPro Guide 2nd Edition

Larry Ullman pdf download

https://ebookgate.com/product/php-5-advanced-visual-quickpro-
guide-2nd-edition-larry-ullman/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

PHP for the Web Visual QuickStart Guide 4th Edition Larry
Ullman

https://ebookgate.com/product/php-for-the-web-visual-quickstart-
guide-4th-edition-larry-ullman/

ebookgate.com

Visual Spatial Thinking for Advanced Learners Grades 3 5


1st Edition Emily Hollett

https://ebookgate.com/product/visual-spatial-thinking-for-advanced-
learners-grades-3-5-1st-edition-emily-hollett/

ebookgate.com

Zend PHP 5 Certification Study Guide Third Edition Davey


Shafik With Ben Ramsey

https://ebookgate.com/product/zend-php-5-certification-study-guide-
third-edition-davey-shafik-with-ben-ramsey/

ebookgate.com

PHP 5 Power Programming 1st Edition Andi Gutmans

https://ebookgate.com/product/php-5-power-programming-1st-edition-
andi-gutmans/

ebookgate.com
Magento PHP Developer s Guide 2nd Edition Allan Macgregor

https://ebookgate.com/product/magento-php-developer-s-guide-2nd-
edition-allan-macgregor/

ebookgate.com

PHP Mysql For Advanced Learning 3rd Edition Hirdesh


Bhardwaj

https://ebookgate.com/product/php-mysql-for-advanced-learning-3rd-
edition-hirdesh-bhardwaj/

ebookgate.com

Advanced Visual Basic 2010 5th Edition Kip R. Irvine

https://ebookgate.com/product/advanced-visual-basic-2010-5th-edition-
kip-r-irvine/

ebookgate.com

Beginning PHP and MySQL 5 From Novice to Professional


Second Edition W. Jason Gilmore

https://ebookgate.com/product/beginning-php-and-mysql-5-from-novice-
to-professional-second-edition-w-jason-gilmore/

ebookgate.com

Beginning PHP 5 and MySQL From Novice to Professional 1st


Edition W Jason Gilmore

https://ebookgate.com/product/beginning-php-5-and-mysql-from-novice-
to-professional-1st-edition-w-jason-gilmore/

ebookgate.com
VISUAL QUICKPRO GUIDE

PHP 5 ADVANCED
Larry Ullman

Peachpit Press
Visual QuickPro Guide
PHP 5 Advanced
Larry Ullman

Peachpit Press
1249 Eighth Street
Berkeley, CA 94710
510/524-2178
510/524-2221 (fax)

Find us on the Web at: www.peachpit.com


To report errors, please send a note to: errata@peachpit.com
Peachpit Press is a division of Pearson Education.
Copyright © 2007 by Larry Ullman

Editor: Rebecca Gulick


Copy Editor: Robert Campbell
Technical Reviewer: Jay Blanchard
Proofreader: Liz Welch
Production Coordinator: Becky Winter
Compositor: Kate Kaminski
Indexer: Karin Arrigoni
Cover Design: Peachpit Press

Notice of Rights
All rights reserved. No part of this book may be reproduced or transmitted in any form by any
means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written
permission of the publisher. For information on getting permission for reprints and excerpts,
contact permissions@peachpit.com.

Notice of Liability
The information in this book is distributed on an “As Is” basis, without warranty. While every
precaution has been taken in the preparation of the book, neither the author nor Peachpit Press
shall have any liability to any person or entity with respect to any loss or damage caused or
alleged to be caused directly or indirectly by the instructions contained in this book or by the
computer software and hardware products described in it.

Trademarks
Visual QuickPro Guide is a registered trademark of Peachpit Press, a division of Pearson
Education.

MySQL is a registered trademark of MySQL AB in the United States and in other countries.
Macintosh and Mac OS X are registered trademarks of Apple Inc. Microsoft, Windows, Windows
XP, and Windows Vista are registered trademarks of Microsoft Corp. Screenshots of Web sites in
this book are copyrighted by the original holders.

Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and Peachpit was aware
of a trademark claim, the designations appear as requested by the owner of the trademark. All
other product names and services identified throughout this book are used in editorial fashion
only and for the benefit of such companies with no intention of infringement of the trademark.
No such use, or the use of any trade name, is intended to convey endorsement or other affilia-
tion with this book.

ISBN-13: 978-0-321-37601-5 ISBN-10: 0-321-37601-3

987654321

Printed and bound in the United States of America


Dedication
To my good friend Michael K. and his family:
I cannot thank you all enough for your con-
tinuing friendship, generosity, and kindness
over these many years.
My utmost thanks to…
Jessica, the love of my life, for just about
everything.
Zoe and Sam, for making my world a
better place.
The grandparents, who traveled far and
often, pitching in with babysitting and
housework so that I might write this book.
Everyone at Peachpit Press for their support,
for their dedication to putting out quality
books, and for everything else they do to
make all this happen.
The most excellent editor, Rebecca Gulick,
for so many reasons.
Bob Campbell, for his spot-on copy editing
and attention to detail.
The production coordinator, Becky Winter,
the compositor, Kate Kaminski, the proof-
reader, Liz Welch, and the indexer, Karin
Arrigoni, who turn my mess of files into an
actual book.
Jay Blanchard, for his technical review.
The readers, the readers, the readers!
Contents at a Glance

Introduction ix
Chapter 1: Advanced PHP Techniques 1
Chapter 2: Developing Web Applications 43
Chapter 3: Advanced Database Concepts 81

Contents at a Glance
Chapter 4: Security Techniques 123
Chapter 5: E-commerce Techniques 169
Chapter 6: Basic Object-Oriented
Programming 233
Chapter 7: Advanced OOP 263
Chapter 8: Real-World OOP 309
Chapter 9: Networking with PHP 347
Chapter 10: PHP and the Server 373
Chapter 11: PHP’s Command-Line Interface 417
Chapter 12: Using PEAR 443
Chapter 13: Ajax 481
Chapter 14: XML and PHP 529
Index 569

v
Table of Contents
Introduction ix
Chapter 1: Advanced PHP Techniques 1
Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . 2
Advanced Function Definitions . . . . . . . . . . . . . . . 18
The Heredoc Syntax . . . . . . . . . . . . . . . . . . . . . . . . . 31
Using printf() and sprintf() . . . . . . . . . . . . . . . . . . . 37
Table of Contents

Chapter 2: Developing Web Applications 43


Documenting Code . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Code Style and Structure . . . . . . . . . . . . . . . . . . . . . 47
Modularizing a Web Site . . . . . . . . . . . . . . . . . . . . . 49
Affecting the Browser Cache . . . . . . . . . . . . . . . . . . 74

Chapter 3: Advanced Database Concepts 81


Storing Sessions in a Database . . . . . . . . . . . . . . . . 82
Working with U.S. Zip Codes . . . . . . . . . . . . . . . . . 96
Creating Stored Functions . . . . . . . . . . . . . . . . . . . 110
Displaying Results Horizontally . . . . . . . . . . . . . . 116

Chapter 4: Security Techniques 123


Remembering the Basics . . . . . . . . . . . . . . . . . . . . 124
Validating Form Data . . . . . . . . . . . . . . . . . . . . . . . 126
Using PECL Filter . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Authentication with PEAR Auth . . . . . . . . . . . . . 143
Using MCrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

Chapter 5: E-commerce Techniques 169


E-commerce Concepts . . . . . . . . . . . . . . . . . . . . . . 170
Creating the Database . . . . . . . . . . . . . . . . . . . . . . 171
Creating the Configuration File . . . . . . . . . . . . . . 183
Making the Template . . . . . . . . . . . . . . . . . . . . . . . 190
Creating the Index Page . . . . . . . . . . . . . . . . . . . . . 197

vi
Table of Contents

Browsing by Category . . . . . . . . . . . . . . . . . . . . . . . 199


Showing a Product . . . . . . . . . . . . . . . . . . . . . . . . . 205
Implementing a Shopping Cart . . . . . . . . . . . . . . 212
Validating Credit Cards . . . . . . . . . . . . . . . . . . . . . 224

Chapter 6: Basic Object-Oriented


Programming 233
OOP Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Defining a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Creating an Object . . . . . . . . . . . . . . . . . . . . . . . . . 240
The $this Attribute . . . . . . . . . . . . . . . . . . . . . . . . . 244
Creating Constructors . . . . . . . . . . . . . . . . . . . . . . 251
Creating Destructors . . . . . . . . . . . . . . . . . . . . . . . 256
Autoloading Classes . . . . . . . . . . . . . . . . . . . . . . . . 260

Chapter 7: Advanced OOP 263

Table of Contents
Advanced Theories . . . . . . . . . . . . . . . . . . . . . . . . . 264
Inheriting Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Inheriting Constructors and Destructors . . . . . 271
Overriding Methods . . . . . . . . . . . . . . . . . . . . . . . . 276
Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Using the Scope Resolution Operator . . . . . . . . . 289
Creating Static Members . . . . . . . . . . . . . . . . . . . . 294
Abstract Classes and Methods . . . . . . . . . . . . . . . 300

Chapter 8: Real-World OOP 309


Catching Exceptions . . . . . . . . . . . . . . . . . . . . . . . . 310
Extending the Exception Class . . . . . . . . . . . . . . 317
Creating a Shopping Cart Class . . . . . . . . . . . . . . 328
Using the Cart Class . . . . . . . . . . . . . . . . . . . . . . . . 340

Chapter 9: Networking with PHP 347


Accessing Other Web Sites . . . . . . . . . . . . . . . . . . 348
Working with Sockets . . . . . . . . . . . . . . . . . . . . . . 355
Performing IP Geolocation . . . . . . . . . . . . . . . . . . 363
Using cURL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368

Chapter 10: PHP and the Server 373


Compressing Files . . . . . . . . . . . . . . . . . . . . . . . . . . 374
PHP-GTK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
Establishing a cron . . . . . . . . . . . . . . . . . . . . . . . . . 399
Scheduling Tasks on Windows . . . . . . . . . . . . . . . 402
Using COM with PHP . . . . . . . . . . . . . . . . . . . . . . . 404

vii
Table of Contents

Chapter 11: PHP’s Command-Line Interface 417


Testing Your Installation . . . . . . . . . . . . . . . . . . . . 418
Executing Bits of Code . . . . . . . . . . . . . . . . . . . . . . 422
Creating a Command-Line Script . . . . . . . . . . . . 424
Running a Command-Line Script . . . . . . . . . . . . 428
Working with Command-Line Arguments . . . . 432
Taking Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437

Chapter 12: Using PEAR 443


Using Benchmark . . . . . . . . . . . . . . . . . . . . . . . . . . 444
Using HTML_QuickForm . . . . . . . . . . . . . . . . . . . 456
Using Mail_Mime . . . . . . . . . . . . . . . . . . . . . . . . . . 469

Chapter 13: Ajax 481


Introduction to Ajax . . . . . . . . . . . . . . . . . . . . . . . . 482
A Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . 484
Table of Contents

Full-Fledged Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . 506


Debugging Ajax Applications . . . . . . . . . . . . . . . . 523

Chapter 14: XML and PHP 529


What Is XML? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
XML Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
Attributes, Empty Elements, and Entities . . . . . 536
Document Type Definitions . . . . . . . . . . . . . . . . . 540
Parsing XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
Creating an RSS Feed . . . . . . . . . . . . . . . . . . . . . . . 562

Index 569

viii
Introduction
i
If you’re looking at this book, then I probably don’t need to tell you how great PHP is.
Presumably, since you’re perusing the pages of an advanced text on the topic, you are
already using PHP for developing dynamic Web sites. Maybe you’ve been doing so for
a couple of years, perhaps just a couple of months. You could have learned PHP on your
own, in a class, or by reading one of the many excellent books on the subject. (I’m
referring not just to my own, of course!) Whatever the case, with some experience

Introduction
under your belt, you probably don’t want another “here’s how to use PHP and isn’t it
swell” book. What you probably want to learn is how to use PHP more efficiently, more
securely, faster, and all-around better than you already are. If so, you’ve found the
right book.
In this humble author’s (or not-so-humble author’s) opinion, advanced PHP is about
learning: how to do different things, how to improve upon the basic things, and about
technologies that intersect with PHP. In short, you know how to make a dynamic Web
site with PHP, but you’d like to know how to make a better Web site, with every possible
meaning of “better.” That’s the approach I’ve taken in writing this book. I’ve not set
out to blow your mind discussing esoteric idiosyncrasies the language has, rewriting
the PHP, MySQL, or Apache source code, or making theoretically interesting but
practically useless code. In short, I present to you several hundred pages of beyond-the-
norm but still absolutely necessary (and often cool) tips and techniques.

ix
Introduction

About This Book


Simply put, I’ve tried to make this book’s
content accessible and useful for every
PHP programmer out there. As I suggest
in the introductory paragraphs, I believe
that “advanced” PHP is mostly a matter
of extended topics. You already possess
all the basic knowledge—you retrieve data-
base query results in your sleep—but want
to go further. This may mean learning object-
oriented programming (OOP), using PEAR
(PHP Extension and Application Repository),
incorporating Ajax (Asynchronous JavaScript
and XML) into a site, or improving upon
aspects of your existing skill set.
My definition of advanced PHP program-
ming covers three loosely grouped skills:
◆ Doing what you already do better, faster,
Introduction

and more securely


◆ Learning more sophisticated PHP tech-
niques
◆ Doing standard things using PHP and
other technologies (like PEAR, Ajax,
or OOP)
This book can be divided into three sections,
corresponding to those skills. The first five
chapters cover advanced PHP knowledge
in general: programming techniques, Web
applications, databases, security, and e-com-
merce. They all cover information that the
average PHP programmer may not be famil-
iar with but should be able to comprehend,
providing useful code in the process.
The next six chapters focus on extending
your knowledge to areas of PHP with which
you might not be as familiar. Half of this sec-
tion goes over object-oriented programming
in great detail, from the fundamentals to
advanced topics to some real-world examples.
The other three chapters are on different ways
you might use PHP: to communicate with

x
Introduction

networked servers, to communicate with


the host server, or from a command-line
interface. The remaining three chapters each
deal with a specific technology tied into
PHP: PEAR, Ajax, and XML.
Two bonus chapters, “Image Generation” and
“Creating PDFs”, can be downloaded from
Peachpit’s Web site. Those two chapters,
which are available for free, provide another
100 pages of content showing how PHP ties
into related, and very useful, technologies.
Visit www.peachpit.com/title/0321376013
to learn how to register this book and
download the chapters.
Most examples used in this book are intended
to be applicable in the real world, omitting
the frivolous code you might see in other
books, tutorials, and manuals. I focus as much
on the philosophies involved as on the coding

Introduction
itself so that, in the end, you will come away
with not just how to do this or that but also
how to apply the overarching mentality to
your own, individual projects.
Unlike with most of my other books, I do
not expect that you’ll necessarily read this
book in sequential order, for the most part.
Some chapters do assume that you’ve read
others, like the object-oriented ones, which
have a progression to them. Some later
chapters also reference examples completed
in earlier ones. If you read the later ones
first, you’ll just need to quickly hop over to
the earlier ones to generate whatever data-
base or scripts the later chapter requires.
Finally, I’ll be using XHTML in my scripts
instead of HTML. I’ll also use some CSS, as
warranted. I do not discuss either of these
subjects in this book (and, to be frank, may
not adhere to them perfectly). If you are not
already familiar with the subjects, you should
look at some online resources or good books
(such as Elizabeth Castro’s excellent Visual
QuickStart Guides) for more information.

xi
Introduction

What’s new in this edition


The most important change in this edition
of the book is that every bit of code has been
updated, rewritten, or replaced to ensure
100 percent compatibility with PHP 5. Many
of the examples have also been modified
to take advantage of features added to the
language.
What is also new is my approach. The first
edition of this text was the second book I
ever wrote. I’ve learned a lot since then, both
in terms of PHP and in terms of what read-
ers expect in a book. A lot of my valuable
experience in this latter category comes
from the constant interactions with other
readers through email and my supporting
forums (www.DMCInsights.com/phorum/). A
fair amount of material is therefore based
upon frequently asked questions I see.
Introduction

How this book compares to my


others
Those readers who have come to this book
from my PHP for the World Wide Web: Visual
QuickStart Guide may find themselves in a
bit over their heads. This book does assume
comfort with standard PHP programming,
in particular debugging your own scripts.
I’m not suggesting you put this book down,
but if you find it goes too fast for you, or
assumes knowledge you don’t currently pos-
sess, you may want to check out my PHP
and MySQL for Dynamic Web Sites: Visual
QuickPro Guide instead.
If you have read the PHP and MySQL book,
or the first edition of this one, I’m hoping
that you’ll find this to be a wonderful addi-
tion to your library and skill set.

xii
Introduction

About PHP 5
Although version 5 of PHP has been out
since July 2004 (when the first non-beta
version was released), there are still a large
number of servers running older versions
of PHP, particularly outside of the United
States. This book does assume you’re using
PHP 5, although some examples will work
with older versions of the language.
The most important change in PHP 5,
with respect to this book, is the completely
different object model and syntax. Object-
oriented programming in PHP 4 is a rather
watered-down concept, really not worth
using in comparison to PHP 5’s OOP. The
object-oriented chapters use PHP 5 syntax
exclusively, and that code will not work on
older versions of the language.

Introduction
In addition, PHP 5 added support for the
Improved MySQL extension, designed for
use with MySQL 4.1 or later. With only one
or two exceptions, I use these Improved
MySQL functions instead of the older, “regu-
lar” MySQL functions. If your PHP installa-
tion (or MySQL installation) does not sup-
port these functions, you’ll need to change
the code accordingly.

xiii
Introduction

What You’ll Need


Just as this book assumes that you already
possess the fundamental skills to program in
PHP (and, more important, to debug it when
things go awry), it also assumes that you
already have everything you need to follow
along with the material. For starters, this
means a PHP-enabled server. At the time of
this writing, the latest version of PHP was
5.2, and much of the book depends upon
your using at least PHP 5.0.
Along with PHP, you’ll often need a database
application. I use MySQL for the examples,
but you can use anything. And, for the scripts
in some of the chapters to work—particularly
the last five—your PHP installation will have
to include support for the corresponding
technology, and that technology’s library
Introduction

may need to be installed, too. Fortunately


PHP 5 comes with built-in support for many
advanced features. If the scripts in a par-
ticular chapter require special extensions,
that will be referenced in the chapter’s intro-
duction. This includes the few times where
I make use of a PEAR or PECL class. Nowhere
in this book will I discuss installation, though,
as I expect you should already know or have
accomplished that.
As with any issue, should you have questions
or problems, you can always search the Web
or post a message in my support forums for
assistance.
Beyond PHP, you need the things you should
already have: a text editor or IDE, an FTP
application (if using a remote server), and a
Web browser. All of the code in this book
has been tested on both Windows XP and
Mac OS X; you’ll see screen shots in both
operating systems.

xiv
Introduction

Support Web Site


I have developed a Web site to support this
book, available at www.DMCinsights.com/
phpvqp2/. This site:

◆ Has every script available for download


◆ Has the SQL commands available for
download
◆ Has extra files, as necessary, available
for download
◆ Lists errors that have been found in
the book
◆ Has a support forum where you can get
help or assist others
◆ Provides a way to contact me directly
When using this site, please make sure

Introduction
you’ve gone to the correct URL (the book’s
title and edition are plastered everywhere).
Each book I’ve written has its own support
area; if you go to the wrong one, the down-
loadable files won’t match those in the book.
Two bonus chapters, “Image Generation”
and “Creating PDFs,” can be downloaded
for free. Visit www.peachpit.com/title/
0321376013 to learn how to register this
book and access the chapters.

xv
This page intentionally left blank
Advanced
PHP Techniques
1
At the most basic level good programming is determined by whether or not an appli-
cation or script works as intended. This is where the beginning programmer will leave
things, and there is nothing wrong with that. However, the advanced programmer
will work past that point, striving toward improved efficiency, reliability, security,
and portability. This book teaches you how to develop the skills of an advanced PHP
programmer.

Advanced PHP techniques


One thing the advanced PHP programmer does better than the beginner is learning to
take advantage of more obscure or harder-to-comprehend features of the language. For
example, while you probably already know how to use arrays, you may not have mas-
tered multidimensional arrays: creating them, sorting them, and so on. You have writ-
ten your own functions by this point but may not understand how to use recursion and
static variables. Issues like these will be discussed as well as other beyond-the-basics
concepts, like the heredoc syntax and the printf()/sprintf() family of functions.

1
Chapter 1

Multidimensional Arrays
Because of their power and flexibility, arrays
are widely used in all PHP programming. For
advanced uses, the multidimensional array
often solves problems where other variable
types just won’t do.
For the first of the two examples, I’ll demon-
strate how to sort a multidimensional array.
It’s a common question users have and isn’t
as hard as one might think. For the second
example, I’ll create a database-driven to-do Figure 1.1 One use of multidimensional
list, which can have limitless dimensions arrays will be to create a nested to-do
list.
(Figure 1.1).

Sorting multidimensional arrays


Sorting arrays is easy using PHP, thanks to
the sort(), ksort(), and related functions.
You can sort a one-dimensional array by key,
Multidimensional Arrays

by value, in reverse order, etc. But these func-


tions will not work on multidimensional
arrays (not as you’d probably like, at least).
Say you have an array defined like so:
$a = array (
array (‘key1’ => 940, ‘key2’ => ‘blah’),
array (‘key1’ => 23, ‘key2’ => ‘this’),
array (‘key1’ => 894, ‘key2’ => ‘that’)
);
Figure 1.2 The multidimensional array
This is a simple two-dimensional array (an sorted by numeric value (key1).
array whose elements are also arrays) that
you might need to sort using key1 (a numeric
sort) or key2 (an alphabetical sort). To sort a
multidimensional array, you define your own
sort function and then tell PHP to use that
function via the usort(), uasort(), or
uksort() function. The function you define
must take exactly two arguments and return
a value indicating which should come first.

2
Advanced PHP Techniques

To sort the preceding array on the first key,


the sorting function would like this:
function mysort1 ($x, $y) {
return ($x[‘key1’] > $y[‘key1’]);
}

Then the PHP code would use this function


by doing:
usort ($a, ‘mysort1’);

Figure 1.2 shows the same array at this


point.
PHP will continue sending the inner arrays
to this function so that they may be sorted. If
you want to see this in detail, print the values
being compared in the function (Figure 1.3).
The usort() function sorts by values and does
not maintain the keys (for the outermost
Figure 1.3 By printing out the values array). If you used uasort(), the keys would
of $x[‘key1’] and $y[‘key1’], one be maintained, and if you used uksort(), the

Multidimensional Arrays
can see how the user-defined sorting sort would be based upon the keys.
function is invoked.
To sort on the second key in the preceding
example, you would want to compare two
strings. That code would be (Figure 1.4
shows the result):
function mysort2 ($x, $y) {
return strcasecmp($x[‘key2’],
➝ $y[‘key2’]);
}
usort ($a, ‘mysort2’);

Or you could just use strcmp(), to perform a


case-sensitive sort.
To see this in action for yourself, let’s run
through an example.

Figure 1.4 An alphabetical sort on


the example array using key2.

3
Chapter 1

To sort a multidimensional array:


1. Create a new PHP script in your text edi-
tor or IDE, starting with the HTML code
(Script 1.1).
<!DOCTYPE html PUBLIC “-//W3C//
➝ DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/
➝ xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/
➝ xhtml” xml:lang=”en” lang=”en”>
<head>
<meta http-equiv=”content-type”
➝ content=”text/html; charset=
➝ iso-8859-1” />
<title>Sorting Multidimensional
➝ Arrays</title>
</head>
<body>
Multidimensional Arrays

<?php # Script 1.1 - sort.php

2. Define a multidimensional array.


$students = array (
256 => array (‘name’ => ‘Jon’,
➝ ‘grade’ => 98.5),
2 => array (‘name’ => ‘Vance’,
➝ ‘grade’ => 85.1),
9 => array (‘name’ => ‘Stephen’,
➝ ‘grade’ => 94.0),
364 => array (‘name’ => ‘Steve’,
➝ ‘grade’ => 85.1),
68 => array (‘name’ => ‘Rob’,
➝ ‘grade’ => 74.6)
);
The outer array, $students, has five ele-
ments, each of which is also an array. The
inner arrays use the student’s ID for the
key (a made-up value) and store two
pieces of data: the student’s name and
their grade.
continues on page 6

4
Advanced PHP Techniques

Script 1.1 This script defines a two-dimensional array, which is then sorted based upon the inner array values.

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4 <head>
5 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
6 <title>Sorting Multidimensional Arrays</title>
7 </head>
8 <body>
9 <?php # Script 1.1 - sort.php
10
11 /* This page creates a multidimensional array
12 * of names and grades.
13 * The array is then sorted twice:
14 * once by name and once by grade.
15 */
16
17 // Create the array:
18 // Array structure:
19 // studentID => array ('name' => 'Name', 'grade' => XX.X)
20 $students = array (
21 256 => array ('name' => 'Jon', 'grade' => 98.5),
22 2 => array ('name' => 'Vance', 'grade' => 85.1),
23 9 => array ('name' => 'Stephen', 'grade' => 94.0),

Multidimensional Arrays
24 364 => array ('name' => 'Steve', 'grade' => 85.1),
25 68 => array ('name' => 'Rob', 'grade' => 74.6)
26 );
27
28 // Name sorting function:
29 function name_sort ($x, $y) {
30 return strcasecmp($x['name'], $y['name']);
31 }
32
33 // Grade sorting function:
34 // Sort in DESCENDING order!
35 function grade_sort ($x, $y) {
36 return ($x['grade'] < $y['grade']);
37 }
38
39 // Print the array as is:
40 echo '<h3>Array As Is</h3><pre>' . print_r($students, 1) . '</pre>';
41
42 // Sort by name:
43 uasort ($students, 'name_sort');
44
45 // Print the array now:
46 echo '<h3>Array Sorted By Name</h3><pre>' . print_r($students, 1) . '</pre>';
47
48 // Sort by grade:
49 uasort ($students, 'grade_sort');
50
51 // Print the array now:
52 echo '<h3>Array Sorted By Grade</h3><pre>' . print_r($students, 1) . '</pre>';
53
54 ?>
55 </body>
56 </html>

5
Chapter 1

3. Define the name sorting function.


function name_sort ($x, $y) {
return strcasecmp($x[‘name’],
➝ $y[‘name’]);
}
The strcasecmp() function returns a
number—negative, 0, or positive—indi-
cating how similar two strings are. If a
negative value is returned, the first string
comes before the second alphabetically; if
a positive value is returned, the second
string comes first. If 0 is returned, the
strings are the same.
4. Define the grade sorting function.
function grade_sort ($x, $y) {
return ($x[‘grade’] <
➝ $y[‘grade’]);
}
Figure 1.5 Failure to use uasort() would
Multidimensional Arrays

This example is like the demo in the cause the keys, which store meaningful
introduction to these steps. One signifi- values (see Script 1.1), to be lost.
cant difference is that I want to perform
a descending sort, so that the highest
grades are listed first. This is easily
accomplished: change the comparison
operator from greater than to less than.
5. Print the array as it’s initially defined.
echo ‘<h3>Array As Is</h3><pre>’ .
➝ print_r($students, 1) . ‘</pre>’;
For improved legibility, I’ll use the <pre>
tags and print_r() to quickly reveal the
arrays’ structure and values.
6. Sort the array by name and print the
results.
uasort ($students, ‘name_sort’);
echo ‘<h3>Array Sorted By
➝ Name</h3><pre>’ .
➝ print_r($students, 1) . ‘</pre>’;
Here the uasort() function is used so
that the keys—the student IDs—are not
lost. Figure 1.5 shows the result if just
usort() was used instead.

6
Advanced PHP Techniques

7. Sort the array by grade and print the 8. Complete the page.
results. ?>
uasort ($students, ‘grade_sort’); </body>
echo ‘<h3>Array Sorted By </html>
➝ Grade</h3><pre>’ .
➝ print_r($students, 1) . ‘</pre>’;
9. Save the file as sort.php, place it in your
Web directory, and test in your Web
browser (Figures 1.6 and 1.7).

Multidimensional Arrays

Figure 1.6 The initial array and sorted Figure 1.7 The array sorted by grade, in
by name. descending order (this is the same Web
page as in Figure 1.6, but it couldn’t all
fit in one screenshot).

7
Chapter 1

Database-driven arrays
If you think about it, most database queries
return a multidimensional array (Figure 1.8).
If the query results are immediately sent to
the Web browser one at a time, the multidi-
mensional structure doesn’t add any compli-
cation to your code. However, if you need to
do something more elaborate with the results, Figure 1.8 Selecting multiple columns from multiple
you’ll need a way to comprehend and man- rows in a database results in a multidimensional
age the nested structure. array.

For this example, I want to create a database-


driven, Web-based to-do list system. If the
to-do list were one-dimensional, this wouldn’t
be that hard. But the list should be nestable,
where each item can have multiple steps.
The result will be a tree-like structure, where
each branch can have its own offshoots
(Figure 1.9).
Multidimensional Arrays

Figure 1.9 How a nested to-do list looks as a tree.

8
Advanced PHP Techniques

The database required by this is surprisingly


simple (Table 1.1). The trick is that each item
has a parent_id attribute. If an item is a sub-
step, its parent_id would be the task number
of the item that it falls under (Figure 1.10).
If an item is not a substep, its parent_id
would be 0. It’s a very simple setup, but han-
dling this in PHP will take some effort.
Over the next few pages, you’ll create the
Figure 1.10 This table represents the same data as in database table and a PHP script for adding
Figures 1.8 and 1.9. There will be a pseudo–foreign new tasks. In the next sections of the chap-
key–primary key relationship between the task_id ter, you’ll see how to use recursive functions
and parent_id columns.
to handle the multidimensional array.

Multidimensional Arrays

Table 1.1 This one database table is all that is required to manage a nested to-do list.

The tasks Table


Column Name Ty p e Extr a

task_id INT UNSIGNED AUTO_INCREMENT, Primary Key


parent_id INT UNSIGNED NOT NULL, DEFAULT 0
task VARCHAR(100) NOT NULL
date_added TIMESTAMP NOT NULL
date_completed TIMESTAMP

9
Chapter 1

To create the database:


1. Access MySQL using the mysql client or
other interface.
I’ll be using MySQL in this example, but
you can use any database application, of
course. To create the table, I’ll use the
command-line mysql client, but you could Figure 1.11 The table will be created within the test
use phpMyAdmin or one of MySQL’s database.
graphical interfaces instead.
2. Select the test database (Figure 1.11).
USE test;
I’ll just throw this one table within the
test database, as it’s not part of any
larger application. You can put it in a
different database, if you prefer.
3. Create the table (Figure 1.12).
CREATE TABLE tasks (
task_id INT UNSIGNED NOT NULL
Multidimensional Arrays

➝ AUTO_INCREMENT, Figure 1.12 Creating the tasks table.

parent_id INT UNSIGNED NOT NULL


➝ DEFAULT 0,
task VARCHAR(100) NOT NULL,
date_added TIMESTAMP NOT NULL,
date_completed TIMESTAMP,
PRIMARY KEY (task_id),
INDEX parent (parent_id),
INDEX added (date_added),
INDEX completed (date_completed)
);
The task_id is an automatically incre-
mented primary key. The value will also
be used as the parent_id if a task is a sub-
step. The task itself goes into a VAR-
CHAR(100) column, which you could also
define as a text type if you wanted to
allow for longer descriptions. Two time-
stamp columns round out the table, one
documenting when the task was added
and another to indicate its completion.
Three standard indexes are placed on
columns that might be used in queries.

10
Advanced PHP Techniques

4. Test the table by adding a dummy task


(Figure 1.13):
INSERT INTO tasks (task) VALUES
➝ (‘Must Do This!’);
SELECT * FROM tasks;

Figure 1.13 The tasks will normally be added using a For a simple task that’s not a subset of
PHP script, but a test insertion is run just to make another task, only the one column needs
sure everything is on the up and up. to be provided with a value. The SELECT
query confirms that the parent_id,
date_added, and date_completed columns
are automatically given default values
(0000-00-00 00:00:00 is the TIMESTAMP
equivalent of 0).
5. Empty the table.
TRUNCATE tasks;

Multidimensional Arrays

11
Chapter 1

To add tasks to the database: <head>


<meta http-equiv=”content-type”
1. Begin a new PHP script in your text edi-
➝ content=”text/html; charset=
tor or IDE, starting with the HTML
➝ iso-8859-1” />
(Script 1.2).
<title>Add a Task</title>
<!DOCTYPE html PUBLIC “-//W3C//
➝ DTD XHTML 1.0 Transitional//EN” </head>

“http://www.w3.org/TR/xhtml1/DTD/ <body>
➝ xhtml1-transitional.dtd”> <?php # Script 1.2 - add_task.php
<html xmlns=”http://www.w3.org/1999/ continues on page 14
➝ xhtml” xml:lang=”en” lang=”en”>

Script 1.2 Tasks are added to the database using this script. Tasks can even be filed under other tasks using the
drop-down menu.

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4 <head>
5 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
6 <title>Add a Task</title>
Multidimensional Arrays

7 </head>
8 <body>
9 <?php # Script 1.2 - add_task.php
10
11 /* This page adds tasks to the tasks table.
12 * The page both displays and handles the form.
13 */
14
15 // Connect to the database:
16 $dbc = @mysqli_connect ('localhost', 'username', 'password', 'test') OR die ('<p>Could not
connect to the database!</p></body></html>');
17
18 // Check if the form has been submitted:
19 if (isset($_POST['submitted']) && !empty($_POST['task'])) {
20
21 // Sanctify the input...
22
23 // The parent_id must be an integer:
24 if (isset($_POST['parent_id'])) {
25 $parent_id = (int) $_POST['parent_id'];
26 } else {
27 $parent_id = 0;
28 }
29
30 // Escape the task:
31 // Assumes Magic Quotes are off!
32 $task = mysqli_real_escape_string($dbc, $_POST['task']);
33
34 // Add the task to the database.
35 $q = "INSERT INTO tasks (parent_id, task) VALUES ($parent_id, '$task')";
36 $r = mysqli_query($dbc, $q);
37
38 // Report on the results:
39 if (mysqli_affected_rows($dbc) == 1) {

12
Advanced PHP Techniques

Script 1.2 continued

40 echo '<p>The task has been added!</p>';


41 } else {
42 echo '<p>The task could not be added!</p>';
43 }
44
45 } // End of submission IF.
46
47 // Display the form:
48 echo '<form action="add_task.php" method="post">
49 <fieldset>
50 <legend>Add a Task</legend>
51
52 <p>Task: <input name="task" type="text" size="60" maxlength="100" /></p>
53
54 <p>Parent Task: <select name="parent_id"><option value="0">None</option>
55 ';
56
57 // Retrieve all the uncompleted tasks:
58 $q = 'SELECT task_id, parent_id, task FROM tasks WHERE date_completed="0000-00-00 00:00:00"
ORDER BY date_added ASC';
59 $r = mysqli_query($dbc, $q);
60
61 // Also store the tasks in an array for use later:
62 $tasks = array();
63

Multidimensional Arrays
64 while (list($task_id, $parent_id, $task) = mysqli_fetch_array($r, MYSQLI_NUM)) {
65
66 // Add to the select menu:
67 echo "<option value=\"$task_id\">$task</option>\n";
68
69 // Add to the array:
70 $tasks[] = array('task_id' => $task_id, 'parent_id' => $parent_id, 'task' => $task);
71
72 }
73
74 echo '</select></p>
75
76 <input name="submitted" type="hidden" value="true" />
77 <input name="submit" type="submit" value="Add This Task" />
78
79 </form>
80 </fieldset>
81 ';
82
83 // Sort the tasks by parent_id:
84 function parent_sort ($x, $y) {
85 return ($x['parent_id'] > $y['parent_id']);
86 }
87 usort ($tasks, 'parent_sort');
88
89 // Display all the tasks:
90 echo '<h3>Current To-Do List</h3><ul>';
91 foreach ($tasks as $task) {
92 echo "<li>{$task['task']}</li>\n";
93 }
94 echo '</ul>';
95 ?>
96 </body>
97 </html>

13
Chapter 1

2. Connect to the database.


$dbc = @mysqli_connect (‘localhost’,
➝ ‘username’, ‘password’, ‘test’) OR
➝ die (‘<p>Could not connect to the
➝ database!</p></body></html>’);
I’ll be using MySQL and the Improved Figure 1.14 If a database connection cannot be made,
MySQL functions in this script. These are this is the result.
available as of PHP 5 and MySQL 4.1. If
you are using older versions of either, you’ll
need to change the code accordingly.
If a database connection couldn’t be
made, an error is printed and the script
terminated (Figure 1.14).
3. Check if the form has been submitted.
if (isset($_POST[‘submitted’]) &&
➝ !empty($_POST[‘task’])) { Figure 1.15 The HTML form for adding tasks.
The form (Figure 1.15) has one main
text box and a drop-down menu. To test
for the form’s submission, the conditional
Multidimensional Arrays

checks that a hidden input named sub-


mitted is set and that the text box
(named task) isn’t empty.
4. Ensure that the parent_id value is an
integer.
if (isset($_POST[‘parent_id’])) {
$parent_id = (int)
➝ $_POST[‘parent_id’];
} else {
$parent_id = 0;
}
The parent_id value is another task’s
task_id. It will come from the drop-down
menu, which means that it should be an
integer. But one shouldn’t make assump-
tions (because if someone hacked the
form to send text as the parent_id, it
would break the query), so this variable is
typecast to an integer. If a valid value is
submitted, this casting will have no effect.
Any invalid values will be turned into 0.
The same applies if the script does not
receive a $_POST[‘parent_id’] value.

14
Advanced PHP Techniques

5. Secure the task value. 8. Complete the submission conditional


$task = and start the form.
➝ mysqli_real_escape_string($dbc, } // End of submission IF.
➝ $_POST[‘task’]); echo ‘<form action=”add_task.php”
The mysqli_real_escape_string() func- ➝ method=”post”>
tion will make whatever submitted task <fieldset>
value safe to use in the query. <legend>Add a Task</legend>
6. Add the task to the database. <p>Task: <input name=”task” type=
$q = “INSERT INTO tasks (parent_id, ➝ ”text” size=”60” maxlength=”100”
➝ task) VALUES ($parent_id, ➝ /></p>
➝ ‘$task’)”; <p>Parent Task: <select name=
$r = mysqli_query($dbc, $q); ➝ ”parent_id”><option value=
➝ ”0”>None</option>
This query differs from the test query
run earlier in that it also populates the ‘;
parent_id field in the table. The form has one text input and one
drop-down menu. The menu will be pop-
7. Report on the query results.
ulated from the list of existing tasks. The
if (mysqli_affected_rows($dbc) == 1)
first possible value will be 0, for tasks that
{
are not subservient to other tasks.

Multidimensional Arrays
echo ‘<p>The task has been
➝ added!</p>’;
9. Retrieve all the uncompleted tasks.
$q = ‘SELECT task_id, parent_id, task
} else {
➝ FROM tasks WHERE its date_
echo ‘<p>The task could not be
➝ completed=”0000-00-00 00:00:00”
➝ added!</p>’;
➝ ORDER BY date_added ASC’;
}
$r = mysqli_query($dbc, $q);
The query returns three pieces of infor-
mation for every uncompleted task
(once a task has been completed, its
date_completed column would have a
nonzero value). The task_id and the task
itself will be used in the drop-down
menu. The parent_id will be used later
to nest the tasks.
continues on next page

15
Chapter 1

10. Create an array for storing the tasks.


$tasks = array();
This script will list all the tasks twice:
once in the drop-down menu and once
after the form (Figure 1.16). This array
will store the second list.
11. Retrieve a database record and use it
accordingly.
while (list($task_id, $parent_id,
➝ $task) = mysqli_fetch_
➝ array($r, MYSQLI_NUM)) {
echo “<option value=\
➝ ”$task_id\”>$task</option>\n”;
$tasks[] = array(‘task_id’ =>
➝ $task_id, ‘parent_id’ =>
➝ $parent_id, ‘task’ => $task); Figure 1.16 The page contains the list of tasks two
} times.

Within the while loop the retrieved


Multidimensional Arrays

record is used to populate the drop-


down menu (Figure 1.17) and is also
stored in the $tasks array. This array will
be multidimensional.
12. Complete the form.
echo ‘</select></p>
<input name=”submitted” type= Figure 1.17 The PHP-generated HTML source code for
➝ ”hidden” value=”true” /> the drop-down menu.

<input name=”submit” type=”submit”


➝ value=”Add This Task” />
</form>
</fieldset>
‘;
The hidden input here is a trick I use
to check for a form’s submission. Doing
this is sometimes necessary as just
pressing Enter within Internet Explorer
for Windows will submit a form without
ever setting the $_POST[‘submit’]
variable.

16
Advanced PHP Techniques

13. Sort the tasks by parent_id.


function parent_sort ($x, $y) {
return ($x[‘parent_id’] >
➝ $y[‘parent_id’]);
}
usort ($tasks, ‘parent_sort’);
The parent_id value is what separates
primary tasks from secondary ones,
so working with this value in PHP is
important. Using the information dis-
cussed earlier in the chapter, a user-
defined function will sort the multidimen-
sional array.
Figure 1.18 Adding a new task that’s not linked to 14. Display the full list of tasks.
another task. echo ‘<h3>Current To-Do
➝ List</h3><ul>’;
foreach ($tasks as $task) {
echo “<li>{$task[‘task’]}

Multidimensional Arrays
➝ </li>\n”;
}
echo ‘</ul>’;
This loop will display each task in order
of its parent_id. This is the first step
toward making the list shown in Figure 1.1,
although as you can see in Figure 1.16,
the list isn’t organized as it should be.
This will be solved later in the chapter.
15. Complete the page.
?>
</body>
</html>

Figure 1.19 Adding a task that’s a subset of an 16. Save the file as add_task.php, place it in
existing task. your Web directory, and test in your Web
browser (Figures 1.18 and 1.19).
✔ Tip
■ If you wanted to implement this idea in a
live site, one improvement you could
make would be the ability to add multi-
ple tasks at once. I’ll provide further tips
on fleshing out this example over the
course of the chapter.
17
Chapter 1

The lack of a condition that determines


Advanced Function when to stop execution of the function cre-
Definitions ates a big programming no-no, the infinite
loop. Compare that function to this one:
Being able to define and use your own func-
function count_to_100 ($n) {
tions is integral to any programming lan-
guage. After even a modicum of PHP experi- if ($n <= 100) {
ence, you’ve no doubt created many. But echo $n . '<br />';
there are three potential features of user- $n++;
defined functions that arise in more count_to_100 ($n);
advanced programming. These are:
}
◆ Recursive functions }
◆ Static variables count_to_100 (1);

◆ Accepting values by reference This function will continue to call itself until
$n is greater than 100, at which point it will
While not often used, sometimes these con- stop executing the function. (That’s obvi-
cepts are indispensable. In discussing and ously a trivial use of this concept; a loop
demonstrating these first two concepts, I’ll would do the same thing.)
continue to build upon the tasks example
Advanced Function Definitions

just begun in the chapter. Recursive functions are necessary when you
have a process that may be followed to an
Recursive functions unknown depth. For example, a script that
searches through a directory may have to
Recursion is the act of a function calling
search through any number of subdirecto-
itself.
ries. Or an array might have an unknown
function somefunction() {
number of dimensions....
// Some code.
With the tasks table created earlier in the
somefunction();
chapter, retrieving and displaying all the
// Possible other code.
tasks is not hard (see Figures 1.17 and 1.18).
} However, the method used in add_task.php
The end result is that your functions can act (Script 1.2) does not properly nest the tasks
both as originally intended and as a loop. like that in Figure 1.1. To accomplish that
The one huge warning when using this tech- desired end, a multidimensional array and a
nique is to make sure your function has an recursive function are required.
“out” clause. For example, the following code
will run ad infinitum:
function add_one ($n) {
$n++;
add_one ($n);
}
add_one (1);

18
Advanced PHP Techniques

To use recursion: <head>


<meta http-equiv=”content-type”
1. Begin a new PHP script in your text edi-
➝ content=”text/html; charset=
tor or IDE, starting with the HTML
➝ iso-8859-1” />
(Script 1.3).
<title>View Tasks</title>
<!DOCTYPE html PUBLIC “-//W3C//
➝ DTD XHTML 1.0 Transitional//EN” </head>

“http://www.w3.org/TR/xhtml1/DTD/ <body>
➝ xhtml1-transitional.dtd”> <h3>Current To-Do List</h3>
<html xmlns=”http://www.w3.org/1999/ <?php # Script 1.3 - view_tasks.php
➝ xhtml” xml:lang=”en” lang=”en”>
continues on page 21

Script 1.3 One recursive function and a potentially bottomless multidimensional array will properly display the
nested list of tasks.

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

Advanced Function Definitions


2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4 <head>
5 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
6 <title>View Tasks</title>
7 </head>
8 <body>
9 <h3>Current To-Do List</h3>
10 <?php # Script 1.3 - view_tasks.php
11
12 /* This page shows all existing tasks.
13 * A recursive function is used to show the
14 * tasks as nested lists, as applicable.
15 */
16
17 // Function for displaying a list.
18 // Receives one argument: an array.
19 function make_list ($parent) {
20
21 // Need the main $tasks array:
22 global $tasks;
23
24 // Start an ordered list:
25 echo '<ol>';
26
27 // Loop through each subarray:
28 foreach ($parent as $task_id => $todo) {
29

(script continues on next page)

19
Chapter 1

Script 1.3 continued

30 // Display the item:


31 echo "<li>$todo";
32
33 // Check for subtasks:
34 if (isset($tasks[$task_id])) {
35
36 // Call this function:
37 make_list($tasks[$task_id]);
38
39 }
40
41 // Complete the list item:
42 echo '</li>';
43
44 } // End of FOREACH loop.
45
46 // Close the ordered list:
47 echo '</ol>';
48
49 } // End of make_list() function.
Advanced Function Definitions

50
51
52 // Connect to the database:
53 $dbc = @mysqli_connect ('localhost', 'username', 'password', 'test') OR die ('<p>Could not
connect to the database!</p></body></html>');
54
55 // Retrieve all the uncompleted tasks:
56 $q = 'SELECT task_id, parent_id, task FROM tasks WHERE date_completed="0000-00-00 00:00:00"
ORDER BY parent_id, date_added ASC';
57 $r = mysqli_query($dbc, $q);
58
59 // Initialize the storage array:
60 $tasks = array();
61
62 while (list($task_id, $parent_id, $task) = mysqli_fetch_array($r, MYSQLI_NUM)) {
63
64 // Add to the array:
65 $tasks[$parent_id][$task_id] = $task;
66
67 }
68
69 // For debugging:
70 //echo '<pre>' . print_r($tasks,1) . '</pre>';
71
72 // Send the first array element
73 // to the make_list() function:
74 make_list($tasks[0]);
75
76 ?>
77 </body>
78 </html>

20
Advanced PHP Techniques

2. Begin defining a function.


function make_list ($parent) {
global $tasks;
echo ‘<ol>’;
The purpose of the function will be
to display an array of items in an
ordered list:
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
This function will take one argument,
which will always be an array. Within the
function, the $tasks array (the main
array) needs to be available—you’ll soon
see why. Then the ordered list is begun.

Advanced Function Definitions


3. Loop through the array, printing
each item.
foreach ($parent as $task_id
➝ => $todo) {
echo “<li>$todo”;
A foreach loop will go through the array,
printing each item within <li> tags.
Those are begun here.
continues on next page

21
Chapter 1

4. Check if any subtasks exist.


if (isset($tasks[$task_id])) {
make_list($tasks[$task_id]);
}
This is the most important part of the
script. The tasks retrieved from the data-
base will be tossed into a multidimen-
sional array like that in Figure 1.20. For
the main array, each key is a parent_id
and the elements are arrays of tasks that
fall under that parent_id. So after print-
ing the initial <li> task, the function
needs to check if this task has any sub-
tasks; in other words: is there an array
element in $tasks whose key is this task
Figure 1.20 The PHP script takes the tasks
ID? If so, then this function should be from the database and creates this
called again, sending that other part of multidimensional array.
the array (the element whose key is this
Advanced Function Definitions

task_id and whose value is an array of


subtasks) as the argument. That will
result in the code:
<ol>
<li>Item 1</li>
<li>Item 2
<ol>
<li>Subitem 1</li>
<li>Subitem 2</li>
</ol>
</li>
<li>Item 3</li>
</ol>

5. Complete the foreach loop and the


function.
echo ‘</li>’;
} // End of FOREACH loop.
echo ‘</ol>’;
} // End of make_list() function.

22
Advanced PHP Techniques

6. Connect to the database. The $tasks array will store every task.
$dbc = @mysqli_connect (‘localhost’, Figure 1.20 shows the final structure. As
➝ ‘username’, ‘password’, ‘test’) OR described in Step 4, the array’s outer-
➝ die (‘<p>Could not connect to the most key is the parent_id value from
➝ database!</p></body></html>’); the table. The value of this outermost
With the recursive function defined, the array is an array of the tasks with that
parent_id.
rest of the script needs to retrieve all the
tasks, organize them in an array, and then 9. Add a debugging line, if desired.
call the make_list() function. //echo ‘<pre>’ . print_r($tasks,1) .
7. Define and execute the query. ➝ ‘</pre>’;

$q = ‘SELECT task_id, parent_id, task When dealing with multidimensional


➝ FROM tasks WHERE arrays, it’s vitally important to know and
date_completed=”0000-00-00 00:00:00” understand the structure you’re working
➝ ORDER BY parent_id, date_added with. When you uncomment this line (by
➝ ASC’; removing the two slashes), the script will
$r = mysqli_query($dbc, $q);
print the array like you see in Figure 1.20.
The query retrieves three pieces of infor- 10. Call the make_list() function, sending it
mation for each task: its ID, its parent_id, the array of top-level tasks.

Advanced Function Definitions


and the task itself. The conditional make_list($tasks[0]);
means that only noncompleted tasks are Although the $tasks variable is a multi-
selected. The results are also ordered by dimensional array, the make_list() func-
the parent_id, so that every top-level task tion needs to be called only once, send-
(with a parent_id of 0) is returned first. A ing it the first array element. This ele-
secondary ordering by the date_added ment’s value is an array of tasks whose
returns the tasks in the order they were parent_id is 0. Within the function, for
added (an assumption being that’s how each of these tasks, a check will see if
they are prioritized). there are subtasks. So the function will
8. Add each task to an array. end up accessing every task thanks to its
$tasks = array();
recursive nature.
while (list($task_id, $parent_id, 11. Complete the page.
➝ $task) = mysqli_fetch_ ?>
➝ array($r, MYSQLI_NUM)) {
</body>
$tasks[$parent_id][$task_id]
</html>
➝= $task;
}
continues on next page

23
Chapter 1

12. Save the file as view_tasks.php, place it


in your Web directory, and test in your
Web browser (Figure 1.21).
13. Add some more subtasks and retest in
your Web browser (Figure 1.22).
✔ Tips
■ The PHP manual suggests that you
should avoid any recursive function that
may call itself over 100 to 200 times.
Doing so could crash the script or the Figure 1.21 The page of tasks, as a bunch of
nested lists.
Web server.
■ This page does assume that some tasks
were returned by the database. You may
want to add a conditional checking that
$tasks isn’t empty prior to calling the
make_list() function.
Advanced Function Definitions

Figure 1.22 There is no limit to the number of


subtasks that this system supports.

24
Advanced PHP Techniques

Using static variables


When working with recursion or, in fact,
any script in which the same function may
be called multiple times, you might want to
consider using the static statement. static
forces the function to remember the value of
a variable from function call to function call,
without using global variables. The example
count_to_100() function (see the preceding
section of this chapter) could be rewritten
like so with the same result:
function count_to_100 () {
static $n = 1;
if ($n <= 100) {
echo $n . '<br />';
$n++;
count_to_100 ();

Advanced Function Definitions


}
Completing This Example }
This example was primarily written to count_to_100 ();
demonstrate multidimensional arrays and
Of course, that’s not a very useful implemen-
recursive functions. Still, it’s a nice exam-
tation of the concept. The very astute reader
ple and worth implementing in a live site
may have wondered how I achieved the result
(the ability to nest tasks is great). If you
in Figure 1.3. Showing the values being com-
wanted to do so, one feature you’d likely
pared is not hard, but counting the iterations
need is the ability to mark a task as com-
requires the use of static. Toward this end,
pleted. An example later in the chapter
sort.php will be modified.
will do just that. Another alteration would
be to change the add_task.php page so
that the drop-down menu reflects the
hierarchy as well.
Another likely addition would be the
ability to add multiple tasks at once. And
you may want to consider an edit task
option. While you’re at it, the view tasks
page could have a link that passes a
value in the URL indicating whether all
tasks should be displayed or just uncom-
pleted ones. These are just some ideas.
Turn to the book’s supporting forum
(www.dmcinsights.com/phorum/) for
assistance and more!

25
Chapter 1

To use static variables: Three lines of code have been added to


the function. The first is the declaration
1. Open sort.php (Script 1.1) in your text of a static variable called $count. It’s ini-
editor or IDE. tially set to 1, but that assignment only
2. Modify the name_sort() function to read applies the first time this function is
(Script 1.4): called (because it’s a static variable).
function name_sort ($x, $y) {
Then the iteration number is printed
(how many times this function has
static $count = 1;
been called), along with the values being
echo “<p>Iteration $count:
compared. Finally, the $count variable is
➝ {$x[‘name’]} vs. {$y[‘name’]}
incremented.
➝ </p>\n”;
$count++;
continues on page 28

return strcasecmp($x[‘name’],
➝ $y[‘name’]);

Script 1.4 This modified version of the sorting script will reveal how many times each sorting function is invoked,
thanks to a static variable.
Advanced Function Definitions

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
4 <head>
5 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
6 <title>Sorting Multidimensional Arrays</title>
7 </head>
8 <body>
9 <?php # Script 1.4 - sort2.php
10
11 /* This page creates a multidimensional array
12 * of names and grades.
13 * The array is then sorted twice:
14 * once by name and once by grade.
15 * A static variable has been added to both
16 * functions to see how many times they are called.
17 */
18
19 // Create the array:
20 // Array structure:
21 // studentID => array ('name' => 'Name', 'grade' => XX.X)
22 $students = array (
23 256 => array ('name' => 'Jon', 'grade' => 98.5),

26
Advanced PHP Techniques

Script 1.4 continued

24 2 => array ('name' => 'Vance', 'grade' => 85.1),


25 9 => array ('name' => 'Stephen', 'grade' => 94.0),
26 364 => array ('name' => 'Steve', 'grade' => 85.1),
27 68 => array ('name' => 'Rob', 'grade' => 74.6)
28 );
29
30 // Name sorting function:
31 function name_sort ($x, $y) {
32 static $count = 1;
33 echo "<p>Iteration $count: {$x['name']} vs. {$y['name']}</p>\n";
34 $count++;
35 return strcasecmp($x['name'], $y['name']);
36 }
37
38 // Grade sorting function:
39 // Sort in DESCENDING order!
40 function grade_sort ($x, $y) {
41 static $count = 1;
42 echo "<p>Iteration $count: {$x['grade']} vs. {$y['grade']}</p>\n";

Advanced Function Definitions


43 $count++;
44 return ($x['grade'] < $y['grade']);
45 }
46
47 // Print the array as is:
48 echo '<h3>Array As Is</h3><pre>' . print_r($students, 1) . '</pre>';
49
50 // Sort by name:
51 uasort ($students, 'name_sort');
52
53 // Print the array now:
54 echo '<h3>Array Sorted By Name</h3><pre>' . print_r($students, 1) . '</pre>';
55
56 // Sort by grade:
57 uasort ($students, 'grade_sort');
58
59 // Print the array now:
60 echo '<h3>Array Sorted By Grade</h3><pre>' . print_r($students, 1) . '</pre>';
61
62 ?>
63 </body>
64 </html>

27
Chapter 1

3. Modify the grade_sort() function


to read:
function grade_sort ($x, $y) {
static $count = 1;
echo “<p>Iteration $count:
➝ {$x[‘grade’]} vs.
➝ {$y[‘grade’]}</p>\n”;
$count++;
return ($x[‘grade’] <
➝ $y[‘grade’]);
}
The same three lines of code that were
added to name_sort() are added to
grade_sort(), except the key being
compared here is grade, not name.
4. Save the file as sort2.php, place it in your
Web directory, and test in your Web
Advanced Function Definitions

browser (Figures 1.23 and 1.24).


Figure 1.23 Sorting the original five-element
array by name requires six calls of the sorting
function.

Figure 1.24 Sorting the same array by grade


also requires six iterations.

28
Another Random Scribd Document
with Unrelated Content
the ancient peoples of the archipelago as the birthplace of the human race; and that
the first brown habitants of Madiana, having been driven from their natural heritage by
the man-eating pirates of the south—the cannibal Caribs,—remembered and mourned
for their sacred mountains, and gave the names of them, for a memory, to the loftiest
summits of their new home,—Hayti.... Surely never was fairer spot hallowed by the
legend of man's nursing-place than the valley blue-shadowed by those peaks,—worthy,
for their gracious femininity of shape, to seem the visible breasts of the All-nourishing
Mother,—dreaming under this tropic sun.
Touching the zone of pale light north-east, appears a beautiful peaked silhouette,—
Dominica. We had hoped to perceive Saint Lucia; but the atmosphere is too heavily
charged with vapor to-day. How magnificent must be the view on certain extraordinary
days, when it reaches from Antigua to the Grenadines—over a range of three hundred
miles! But the atmospheric conditions which allow of such a spectacle are rare indeed.
As a general rule, even in the most unclouded West Indian weather, the loftiest peaks
fade into the light at a distance of one hundred miles.
A sharp ridge covered with fern cuts off the view of the northern slopes: one must
climb it to look down upon Macouba. Macouba occupies the steepest slope of Pelée,
and the grimmest part of the coast: its little chef-lieu is industrially famous for the
manufacture of native tobacco, and historically for the ministrations of Père Labat, who
rebuilt its church. Little change has taken place in the parish since his time. "Do you
know Macouba?" asks a native writer;—"it is not Pelion upon Ossa, but ten or twelve
Pelions side by side with ten or twelve Ossæ, interseparated by prodigious ravines.
Men can speak to each other from places whence, by rapid walking, it would require
hours to meet;—to travel there is to experience on dry land the sensation of the sea."
With the diminution of the warmth provoked by the exertion of climbing, you begin to
notice how cool it feels;—you could almost doubt the testimony of your latitude.
Directly east is Senegambia: we are well south of Timbuctoo and the Sahara,—on a
line with southern India. The ocean has cooled the winds; at this altitude the rarity of
the air is northern; but in the valleys below the vegetation is African. The best
alimentary plants, the best forage, the flowers of the gardens, are of Guinea;—the
graceful date-palms are from the Atlas region: those tamarinds, whose thick shade
stifles all other vegetal life beneath it, are from Senegal. Only, in the touch of the air,
the vapory colors of distance, the shapes of the hills, there is a something not of
Africa: that strange fascination which has given to the island its poetic creole name,—
le Pays des Revenants. And the charm is as puissant in our own day as it was more
than two hundred years ago, when Père Du Tertre wrote:—"I have never met one
single man, nor one single woman, of all those who came back therefrom, in whom I
have not remarked a most passionate desire to return thereunto."
Time and familiarity do not weaken the charm, either for those born among these
scenes who never voyaged beyond their native island, or for those to whom the streets
of Paris and the streets of St. Pierre are equally well known. Even at a time when
Martinique had been forsaken by hundreds of her ruined planters, and the paradise-life
of the old days had become only a memory to embitter exile,—a Creole writes:—
—"Let there suddenly open before you one of those vistas, or anses, with colonnades
of cocoa-palm—at the end of which you see smoking the chimney of a sugar-mill, and
catch a glimpse of the hamlet of negro cabins (cases);—or merely picture to yourself
one of the most ordinary, most trivial scenes: nets being hauled by two ranks of
fishermen; a canot waiting for the embellie to make a dash for the beach; even a
negro bending under the weight of a basket of fruits, and running along the shore to
get to market;—and illuminate that with the light of our sun! What landscapes!—O
Salvator Rosa! O Claude Lorrain,—if I had your pencil!... Well do I remember the day
on which, after twenty years of absence, I found myself again in presence of these
wonders;—I feel once more the thrill of delight that made all my body tremble, the
tears that came to my eyes. It was my land, my own land, that appeared so
beautiful."...[36]

[36]Dr. E. Rufz: "Études historiques," vol. I, p. 180.

At the beginning, while gazing south, east, west, to the rim of the world, all laughed,
shouted, interchanged the quick delight of new impressions: every face was radiant....
Now all look serious;—none speak. The first physical joy of finding oneself on this point
in violet air, exalted above the hills, soon yields to other emotions inspired by the
mighty vision and the colossal peace of the heights. Dominating all, I think, is the
consciousness of the awful antiquity of what one is looking upon,—such a sensation,
perhaps, as of old found utterance in that tremendous question of the Book of Job:
—"Wast thou brought forth before the hills?"
RUINS, ST. PIERRE
Decked out with flowers grayed by the
passing years, these crumbling walls look
immeasurably old.
... And the blue multitude of the peaks, the perpetual congregation of the mornes,
seem to chorus in the vast resplendence,—telling of Nature's eternal youth, and the
passionless permanence of that about us and beyond us and beneath,—until
something like the fulness of a great grief begins to weigh at the heart.... For all this
astonishment of beauty, all this majesty of light and form and color, will surely endure,
—marvellous as now,—after we shall have lain down to sleep where no dreams come,
and may never arise from the dust of our rest to look upon it.
'TI CANOTIÉ

One might almost say that commercial time in St. Pierre is measured by
cannon-shots,—by the signal-guns of steamers. Every such report announces
an event of extreme importance to the whole population. To the merchant it is
a notification that mails, money, and goods have arrived;—to consuls and
Government officials it gives notice of fees and dues to be collected;—for the
host of lightermen, longshoremen, port laborers of all classes, it promises
work and pay;—for all it signifies the arrival of food. The island does not feed
itself: cattle, salt meats, hams, lard, flour, cheese, dried fish, all come from
abroad,—particularly from America. And in the minds of the colored
population the American steamer is so intimately associated with the idea of
those great tin cans in which food-stuffs are brought from the United States,
that the onomatope applied to the can, because of the sound outgiven by it
when tapped,—bom!—is also applied to the ship itself. The English or French
or Belgian steamer, however large, is only known as packett-à, batiment-là;
but the American steamer is always the "bom-ship"—batiment-bom-à; or, the
"food-ship"—batiment-mangé-à. ... You hear women and men asking each other, as
the shock of the gun flaps through all the town, "Mil godé ça qui là, chè?" And if the
answer be, "Mais c'est bom-là, chè,—bom-mangé-à ka rivé" (Why, it is the bom, dear,
—the food-bom that has come), great is the exultation.
Again, because of the sound of her whistle, we find a steamer called in this same
picturesque idiom, batiment-cône,—"the horn-ship." There is even a song, of which the
refrain is:—
"Bom-là rivé, chè,—
Batiment-cône-là rivé."
... But of all the various classes of citizens, those most joyously excited by the coming
of a great steamer, whether she be a "bom" or not,—are the 'ti canotié, who swarm
out immediately in little canoes of their own manufacture to dive for coins which
passengers gladly throw into the water for the pleasure of witnessing the graceful
spectacle. No sooner does a steamer drop anchor—unless the water be very rough
indeed—than she is surrounded by a fleet of the funniest little boats imaginable, full of
naked urchins screaming creole.

These 'ti canotié—these little canoe-boys and professional divers—are, for the most
part, sons of boatmen of color, the real canotiers. I cannot find who first invented the
'ti canot: the shape and dimensions of the little canoe are fixed according to a tradition
several generations old; and no improvements upon the original model seem to have
ever been attempted, with the sole exception of a tiny water-tight box contrived
sometimes at one end, in which the palettes, or miniature paddles, and various other
trifles may be stowed away. The actual cost of material for a canoe of this kind seldom
exceeds twenty-five or thirty cents; and, nevertheless, the number of canoes is not
very large—I doubt if there be more than fifteen in the harbor;—as the families of
Martinique boatmen are all so poor that twenty-five sous are difficult to spare, in spite
of the certainty that the little son can earn fifty times the amount within a month after
owning a canoe.
For the manufacture of a canoe an American lard-box or kerosene-oil box is preferred
by reason of its shape; but any well-constructed shipping-case of small size would
serve the purpose. The top is removed; the sides and the corners of the bottom are
sawn out at certain angles; and the pieces removed are utilized for the sides of the
bow and stern,—sometimes also in making the little box for the paddles, or palettes,
which are simply thin pieces of tough wood about the form and size of a cigar-box lid.
Then the little boat is tarred and varnished: it cannot sink,—though it is quite easily
upset. There are no seats. The boys (there are usually two to each canot) simply squat
down in the bottom,—facing each other. They can paddle with surprising swiftness
over a smooth sea; and it is a very pretty sight to witness one of their prize contests in
racing,—which take place every 14th of July....

II

... It was five o'clock in the afternoon: the horizon beyond the harbor was turning
lemon-color;—and a thin warm wind began to come in weak puffs from the south-
west,—the first breaths to break the immobility of the tropical air. Sails of vessels
becalmed at the entrance of the bay commenced to flap lazily: they might belly after
sundown.
The La Guayra was in port, lying well out: her mountainous iron mass rising high above
the modest sailing craft moored in her vicinity,—barks and brigantines and brigs and
schooners and barkentines. She had lain before the town the whole afternoon,
surrounded by the entire squadron of canots; and the boys were still circling about her
flanks, although she had got up steam and was lifting her anchor. They had been very
lucky, indeed, that afternoon,—all the little canotiers;—and even many yellow lads, not
fortunate enough to own canoes, had swum out to her in hope of sharing the silver
shower falling from her saloon-deck. Some of these, tired out, were resting themselves
by sitting on the slanting cables of neighboring ships. Perched naked thus,—balancing
in the sun, against the blue of sky or water, their slender bodies took such orange from
the mellowing light as to seem made of some self-luminous substance,—flesh of sea-
fairies....
Suddenly the La Guayra opened her steam-throat and uttered such a moo that all the
mornes cried out for at least a minute after;—and the little fellows perched on the
cables of the sailing craft tumbled into the sea at the sound and struck out for shore.
Then the water all at once burst backward in immense frothing swirls from beneath the
stem of the steamer; and there arose such a heaving as made all the little canoes
dance. The La Guayra was moving. She moved slowly at first, making a great fuss as
she turned round: then she began to settle down to her journey very majestically,—
just making the water pitch a little behind her, as the hem of a woman's robe tosses
lightly at her heels while she walks.
And, contrary to custom, some of the canoes followed after her. A dark handsome
man, wearing an immense Panama hat, and jewelled rings upon his hands, was still
throwing money; and still the boys dived for it. But only one of each crew now
plunged; for, though the La Guayra was yet moving slowly, it was a severe strain to
follow her, and there was no time to be lost.
The captain of the little band—black Maximilien, ten years old, and his comrade
Stéphane—nicknamed Ti Chabin, because of his bright hair,—a slim little yellow boy of
eleven—led the pursuit, crying always, "Encò, Missié,—encò!"...
The La Guayra had gained fully two hundred yards when the handsome passenger
made his final largess,—proving himself quite an expert in flinging coin. The piece fell
far short of the boys, but near enough to distinctly betray a yellow shimmer as it
twirled to the water. That was gold!
In another minute the leading canoe had reached the spot, the other canotiers
voluntarily abandoning the quest,—for it was little use to contend against Maximilien
and Stéphane, who had won all the canoe contests last 14th of July. Stéphane, who
was the better diver, plunged.
He was much longer below than usual, came up at quite a distance, panted as he
regained the canoe, and rested his arms upon it. The water was so deep there, he
could not reach the coin the first time, though he could see it: he was going to try
again,—it was gold, sure enough.
—"Fouinq! ça fond içitt!" he gasped.
Maximilien felt all at once uneasy. Very deep water, and perhaps sharks. And sunset
not far off! The La Guayra was diminishing in the offing.
—"Boug-là 'lé fai nou néyé!—laissé y, Stéphane!" he cried. (The fellow wants to drown
us. Laissé—leave it alone.)
But Stéphane had recovered breath, and was evidently resolved to try again. It was
gold!
—"Mais ça c'est lò!"
—"Assez, non!" screamed Maximilien. "Pa plongé ncò, moin ka di ou! Ah! foute!"...
Stéphane had dived again!
... And where were the others? "Bon-Dié, gadé oti yo yé!" They were almost out of
sight,—tiny specks moving shoreward.... The La Guayra now seemed no bigger than
the little packet running between St. Pierre and Fort-de-France.
Up came Stéphane again, at a still greater distance than before,—holding high the
yellow coin in one hand. He made for the canoe, and Maximilien paddled towards him
and helped him in. Blood was streaming from the little diver's nostrils, and blood
colored the water he spat from his mouth.
—"Ah! moin té ka di ou laissé y!" cried Maximilien, in anger and alarm.... "Gàdé, godé
sang-à ka coulé nans nez ou,—nans bouche ou!... Mi oti lézautt!"
Lézautt, the rest, were no longer visible.
—"Et mi oti nou yé!" cried Maximilien again. They had never ventured so far from
shore.
But Stéphane answered only, "C'est lò!" For the first time in his life he held a piece of
gold in his fingers. He tied it up in a little rag attached to the string fastened about his
waist,—a purse of his own invention,—and took up his paddles, coughing the while and
spitting crimson.
—"Mi! mi!—mi oti nou yé!" reiterated Maximilien. "Bon-Dié! look where we are!"
The Place had become indistinct;—the light-house, directly behind half an hour earlier,
now lay well south: the red light had just been kindled. Seaward, in advance of the
sinking orange disk of the sun, was the La Guayra, passing to the horizon. There was
no sound from the shore: about them a great silence had gathered,—the Silence of
seas, which is a fear. Panic seized them: they began to paddle furiously.
But St. Pierre did not appear to draw any nearer. Was it only an effect of the dying
light, or were they actually moving towards the semicircular cliffs of Fond-Corré?...
Maximilien began to cry. The little chabin paddled on,—though the blood was still
trickling over his breast.
Maximilien screamed out to him:—
—"Ou pa ka pagayé,—anh?—ou ni bousoin demi??" (Thou dost not paddle, eh?—thou
wouldst go to sleep?)
—"Si! moin ka pagayé,—epi fò!" (I am paddling, and hard, too!) responded
Stéphane....
—"Ou ka pagayé!—ou ka menti!" (Thou art paddling!—thou liest!) vociferated
Maximilien.... "And the fault is all thine. I cannot, all by myself, make the canoe to go
in water like this! The fault is all thine: I told thee not to dive, thou stupid!"
—"Ou fou!" cried Stéphane, becoming angry. "Moin ka pagayé!" (I am paddling.)
—"Beast! never may we get home so! Paddle, thou lazy;—paddle, thou nasty!"
—"Macaque thou!—monkey!"
—"Chabin!—must be chabin, for to be stupid so!"
—"Thou black monkey!—thou species of ouistiti!"
—"Thou tortoise-of-the-land!—thou slothful more than molocoye!"
—"Why, thou cursed monkey, if thou sayest I do not paddle, thou dost not know how
to paddle!"...
... But Maximilien's whole expression changed: he suddenly stopped paddling, and
stared before him and behind him at a great violet band broadening across the sea
northward out of sight; and his eyes were big with terror as he cried out:—
—"Mais ni qui chose qui douôle içitt!... There is something queer, Stéphane; there is
something queer."...
—"Ah! you begin to see now, Maximilien!—it is the current!"
—"A devil-current, Stéphane.... We are drifting: we will go to the horizon!"...
To the horizon—"nou kallé Ihorizon!"—a phrase of terrible picturesqueness.... In the
creole tongue, "to the horizon" signifies to the Great Open—into the measureless sea.
—"C'est pa lapeine pagayé atouèlement!" (It is no use to paddle now), sobbed
Maximilien, laying down his palettes.
—"Si! si!" said Stéphane, reversing the motion: "paddle with the current."
—"With the current! It runs to La Dominique!"
—"Pouloss," phlegmatically returned Stéphane,—"ennou!—let us make for La
Dominique!"
—"Thou fool!—it is more than past forty kilometres.... Stéphane, mi! gadé!—mi qui
gouôs requ'em!"
A long black fin cut the water almost beside them, passed, and vanished,—a requin
indeed! But, in his patois, the boy almost re-echoed the name as uttered by quaint
Père Du Tertre, who, writing of strange fishes more than two hundred years ago, says
it is called REQUIEM, because for the man who findeth himself alone with it in the
midst of the sea, surely a requiem must be sung.
—"Do not paddle, Stéphane!—do not put thy hand in the water again!"

III

... The La Guayra was a point on the sky-verge;—the sun's face had vanished. The
silence and the darkness were deepening together.
—"Si lanmè ka vini plis fò, ça nou ké fai?" (If the sea roughens, what are we to do?)
asked Maximilien.
—"Maybe we will meet a steamer," answered Stéphane: "the Orinoco was due to-day."
—"And if she pass in the night?"
—"They can see us."...
—"No, they will not be able to see us at all. There is no moon."
—"They have lights ahead."
—"I tell thee, they will not see us at all,—pièss! pièss!"
—"Then they will hear us cry out."
—"No,—we cannot cry so loud. One can hear nothing but a steam-whistle or a cannon,
with the noise of the wind and the water and the machine.... Even on the Fort-de-
France packet one cannot hear for the machine. And the machine of the Orinoco is
more big than the church of the 'Centre.'"
—"Then we must try to get to La Dominique."
... They could now feel the sweep of the mighty current;—it even seemed to them that
they could hear it,—a deep low whispering. At long intervals they saw lights,—the
lights of houses in Pointe-Prince, in Fond-Canonville,—in Au Prêcheur. Under them the
depth was unfathomed:—hydrographic charts mark it sans-fond. And they passed the
great cliffs of Aux Abymes, under which lies the Village of the Abysms.
The red glare in the west disappeared suddenly as if blown out;—the rim of the sea
vanished into the void of the gloom;—the night narrowed about them, thickening like a
black fog. And the invisible, irresistible power of the sea was now bearing them away
from the tall coast,—over profundities unknown,—over the sans-fond,—out "to the
horizon."
IV

... Behind the canoe a long thread of pale light quivered and twisted: bright points
from time to time mounted up, glowered like eyes, and vanished again;—glimmerings
of faint flame wormed away on either side as they floated on. And the little craft no
longer rocked as before;—they felt another and a larger motion,—long slow ascents
and descents enduring for minutes at a time;—they were riding the great swells,—
riding the horizon!
Twice they were capsized. But happily the heaving was a smooth one, and their little
canoe could not sink: they groped for it, found it, righted it, and climbed in, and baled
out the water with their hands.
From time to time they both cried out together, as loud as they could,—"Sucou!—
sucou!—sucou!"—hoping that some one might be looking for them.... The alarm had
indeed been given; and one of the little steam-packets had been sent out to look for
them,—with torch-fires blazing at her bows; but she had taken the wrong direction.
—"Maximilien," said Stéphane, while the great heaving seemed to grow vaster,—"fau
nou ka prié Bon-Dié."...
Maximilien answered nothing.
—"Fau prié Bon-Dié" (We must pray to the Bon-Dié), repeated Stéphane.
—"Pa lapeine, li pas pè ouè nou atò!" (It is not worth while: He cannot see us now)
answered the little black.
... In the immense darkness even the loom of the island was no longer visible.
—"O Maximilien!—Bon-Dié ka ouè toutt, ha connaitt toutt" (He sees all; He knows all),
cried Stéphane.
—"Y pa pè ouè non pièss atouèlement, moin ben sur!" (He cannot see us at all now,—I
am quite sure) irreverently responded Maximilien....
—"Thou thinkest the Bon-Dié like thyself!—He has not eyes like thou," protested
Stéphane. "Li pas ka tiny coulé; li pas ka tini zié" (He has not color; He has not eyes),
continued the boy, repeating the text of his catechism,—the curious creole catechism
of old Perè Goux, of Carbet. [Quaint priest and quaint catechism have both passed
away.]
—"Moin pa save si li pa ka tini coulè" (I know not if He has not color), answered
Maximilien. "But what I well know is that if He has not eyes. He cannot see.... Fouinq!
—how idiot!"
—"Why, it is in the Catechism," cried Stéphane.... "'Bon-Dié, li conm vent: vent tout-
patout, et nou pa save ouè li;—li ka touché nou,—li ka boulvésé lamnè." (The Good-
God is like the Wind: the Wind is everywhere, and we cannot see It;—It touches us,—
It tosses the sea.)
—"If the Bon-Dié is the Wind," responded Maximilien, "then pray thou the Wind to stay
quiet."
—"The Bon-Dié is not the Wind," cried Stéphane: "He is like the Wind, but He is not
the Wind."...
—"Ah! soc-soc!—fouinq!... More better past praying to care we be not upset again and
eaten by sharks."
***************
... Whether the little chabin prayed either to the Wind or to the Bon-Dié, I do not
know. But the Wind remained very quiet all that night,—seemed to hold its breath for
fear of ruffling the sea. And in the Mouillage of St. Pierre furious American captains
swore at the Wind because it would not fill their sails.

Perhaps, if there had been a breeze, neither Stéphane nor Maximilien would have seen
the sun again. But they saw him rise.
Light pearled in the east, over the edge of the ocean, ran around the rim of the sky
and yellowed: then the sun's brow appeared;—a current of gold gushed rippling across
the sea before him;—and all the heaven at once caught blue fire from horizon to
zenith. Violet from flood to cloud the vast recumbent form of Pelée loomed far behind,
—with long reaches of mountaining: pale grays o'ertopping misty blues. And in the
north another lofty shape was towering,—strangely jagged and peaked and beautiful,
—the silhouette of Dominica: a sapphire saw!... No wandering clouds:—over far Pelée
only a shadowy piling of nimbi.... Under them the sea swayed dark as purple ink—a
token of tremendous depth.... Still a dead calm, and no sail in sight.
—"Ça c'est la Dominique," said Maximilien,—"Ennou pou ouivage-à!"
They had lost their little palettes during the night;—they used their naked hands, and
moved swiftly. But Dominica was many and many a mile away. Which was the nearer
island, it was yet difficult to say;—in the morning sea-haze, both were vapory,—
difference of color was largely due to position....
Sough!—sough!—sough!—A bird with a white breast passed overhead; and they
stopped paddling to look at it,—a gull. Sign of fair weather!—it was making for
Dominica.
—"Moin ni ben faim," murmured Maximilien. Neither had eaten since the morning of
the previous day,—most of which they had passed sitting in their canoe.
—"Moin ni anni soif," said Stéphane. And besides his thirst he complained of a burning
pain in his head, always growing worse. He still coughed, and spat out pink threads
after each burst of coughing.
The heightening sun flamed whiter and whiter: the flashing of waters before his face
began to dazzle like a play of lightning.... Now the islands began to show sharper lines,
stronger colors; and Dominica was evidently the nearer;—for bright streaks of green
were breaking at various angles through its vapor-colored silhouette, and Martinique
still remained all blue.
... Hotter and hotter the sun burned; more and more blinding became his
reverberation. Maximilien's black skin suffered least; but both lads, accustomed as they
were to remaining naked in the sun, found the heat difficult to bear. They would gladly
have plunged into the deep water to cool themselves, but for fear of sharks;—all they
could do was to moisten their heads, and rinse their mouths with sea-water.
Each from his end of the canoe continually watched the horizon. Neither hoped for a
sail, there was no wind; but they looked for the coining of steamers,—the Orinoco
might pass, or the English packet, or some one of the small Martinique steamboats
might be sent out to find them.
Yet hours went by; and there still appeared no smoke in the ring of the sky,—never a
sign in all the round of the sea, broken only by the two huge silhouettes.... But
Dominica was certainly nearing;—the green lights were spreading through the
luminous blue of her hills.
... Their long immobility in the squatting posture began to tell upon the endurance of
both boys,—producing dull throbbing aches in thighs, hips, and loins.... Then, about
mid-day, Stéphane declared he could not paddle any more;—it seemed to him as if his
head must soon burst open with the pain which filled it: even the sound of his own
voice hurt him,—he did not want to talk.

VI

... And another oppression came upon them,—in spite of all the pains, and the blinding
dazzle of waters, and the biting of the sun: the oppression of drowsiness. They began
to doze at intervals,—keeping their canoe balanced in some automatic way,—as cavalry
soldiers, overweary, ride asleep in the saddle.
But at last, Stéphane, awaking suddenly with a paroxysm of coughing, so swayed
himself to one side as to overturn the canoe; and both found themselves in the sea.
Maximilien righted the craft, and got in again; but the little chabin twice fell back in
trying to raise himself upon his arms. He had become almost helplessly feeble.
Maximilien, attempting to aid him, again overturned the unsteady little boat; and this
time it required all his skill and his utmost strength to get Stéphane out of the water.
Evidently Stéphane could be of no more assistance;—the boy was so weak he could
not even sit up straight.
—"Aïe! ou kê jété nou encò," panted Maximilien,—"metté ou toutt longue."
Stéphane slowly let himself down, so as to lie nearly all his length in the canoe,—one
foot on either side of Maximilien's hips. Then he lay very still for a long time,—so still
that Maximilien became uneasy.
—"Ou ben malade?" he asked.... Stéphane did not seem to hear: his eyes remained
closed.
—"Stéphane!" cried Maximilien, in alarm,—"Stéphane!"
—"C'est lò, papoute," murmured Stéphane, without lifting his eyelids,—"ça c'est lò!—ou
pa janmain cuè yon bel pièce conm ça?" (It is gold, little father.... Didst thou ever see a
pretty piece like that?... No, thou wilt not beat me, little father?—no, papoute!)
—"Ou ka dòmi, Stéphane?"—queried Maximilien, wondering,—"art asleep?"
But Stéphane opened his eyes and looked at him so strangely! Never had he seen
Stéphane look that way before.
—"Ça ou ni, Stéphane?—what ails thee?—aïe! Bon-Dié, Bon-Dié?"
—"Bon-Dié!"—muttered Stéphane, closing his eyes again at the sound of the great
Name,—"He has no color;—He is like the Wind."...
—"Stéphane!"...
—"He feels in the dark;—He has not eyes."...
—"Stéphane, pa pàlé ça!"
—"He tosses the sea.... He has no face;—He lifts up the dead... and the leaves."...
ARMISTICE DAY, FORT-DE-FRANCE
A review at 7 A. M. by the governor anti his
staff, all in evening dress, with cannons
booming as noisily as in the north—followed
by a day busily devoted to doing nothing.
—"Ou fou!" cried Maximilien, bursting into a wild fit of sobbing,—"Stéphane, thou art
mad!"
And all at once he became afraid of Stéphane,—afraid of all he said,—afraid of his
touch,—afraid of his eyes... he was growing like a zombi!
But Stéphane's eyes remained closed;—he ceased to speak.
... About them deepened the enormous silence of the sea;—low swung the sun again.
The horizon was yellowing: day had begun to fade. Tall Dominica was now half green;
but there yet appeared no smoke, no sail, no sign of life.
And the tints of the two vast Shapes that shattered the rim of the light shifted as if
evanescing,—shifted like tones of West Indian fishes,—of pisquette and congre,—of
caringue and gouôs-zié and balaou. Lower sank the sun;—cloud-fleeces of orange
pushed up over the edge of the west;—a thin warm breath caressed the sea,—sent
long lilac shudderings over the flanks of the swells. Then colors changed again: violet
richened to purple;—greens blackened softly;—grays smouldered into smoky gold.
And the sun went down.
VII

And they floated into the fear of the night together. Again the ghostly fires began to
wimple about them: naught else was visible but the high stars.
Black hours passed. From minute to minute Maximilien cried out:—"Sucou! sucou!"
Stéphane lay motionless and dumb: his feet, touching Maximilien's naked hips, felt
singularly cold.
... Something knocked suddenly against the bottom of the canoe,—knocked heavily—
making a hollow loud sound. It was not Stéphane;—Stéphane lay still as a stone: it
was from the depth below. Perhaps a great fish passing.
It came again,—twice,—shaking the canoe like a great blow. Then Stéphane suddenly
moved,—drew up his feet a little,—made as if to speak:—"Ou..."; but the speech failed
at his lips,—ending in a sound like the moan of one trying to call out in sleep;—and
Maximilien's heart almost stopped beating.... Then Stéphane's limbs straightened
again; he made no more movement;—Maximilien could not even hear him breathe....
All the sea had begun to whisper.
A breeze was rising;—Maximilien felt it blowing upon him. All at once it seemed to him
that he had ceased to be afraid,—that he did not care what might happen. He thought
about a cricket he had one day watched in the harbor,—drifting out with the tide, on
an atom of dead bark,—and he wondered what had become of it. Then he understood
that he himself was the cricket,—still alive. But some boy had found him and pulled off
his legs. There they were,—his own legs, pressing against him: he could still feel the
aching where they had been pulled off; and they had been dead so long they were
now quite cold.... It was certainly Stéphane who had pulled them off....
The water was talking to him. It was saying the same thing over and over again,—
louder each time, as if it thought he could not hear. But he heard it very well:—"Bon-
Dié, li conm vent... li ka touché nou... nou pa save ouè li." (But why had the Bon-Dié
shaken the wind?) "Li pa ka tint zié," answered the water.... Ouille!—He might all the
same care not to upset folks in the sea!... Mi!...
But even as he thought these things, Maximilien became aware that a white, strange,
bearded face was looking at him: the Bon-Dié was there,—bending over him with a
lantern,—talking to him in a language he did not understand. And the Bon-Dié certainly
had eyes,—great gray eyes that did not look wicked at all. He tried to tell the Bon-Dié
how sorry he was for what he had been saying about him;—but found he could not
utter a word. He felt great hands lift him up to the stars, and lay him down very near
them,—just under them. They burned blue-white, and hurt his eyes like lightning:—he
felt afraid of them.... About him he heard voices,—always speaking the same language,
which he could not understand.... "Poor little devils!—poor little devils!" Then he heard
a bell ring; and the Bon-Dié made him swallow something nice and warm;—and
everything became black again. The stars went out!...
... Maximilien was lying under an electric-light on board the great steamer Rio de
Janeiro, and dead Stéphane beside him.... It was four o'clock in the morning.

LA FILLE DE COULEUR

Nothing else in the picturesque life of the French colonies of the Occident
impresses the traveller on his first arrival more than the costumes of the
women of color. They surprise the aesthetic sense agreeably;—they are local
and special: you will see nothing resembling them among the populations of
the British West Indies; they belong to Martinique, Guadeloupe, Désirade,
Marie-Galante, and Cayenne,—in each place differing sufficiently to make the
difference interesting, especially in regard to the head-dress. That of
Martinique is quite Oriental;—more attractive, although less fantastic than the
Cayenne coiffure, or the pretty drooping mouchoir of Guadeloupe.
These costumes are gradually disappearing, for various reasons,—the chief
reason being of course the changes in the social condition of the colonies
during the last forty years. Probably the question of health had also
something to do with the almost universal abandonment in Martinique of the
primitive slave dress,—chemise and jupe,—which exposed its wearer to
serious risks of pneumonia; for as far as economical reasons are concerned, there was
no fault to find with it: six francs could purchase it when money was worth more than
it is now. The douillette, a long trailing dress, one piece from neck to feet, has taken its
place.[37] But there was a luxurious variety of the jupe costume which is disappearing
because of its cost; there is no money in the colonies now for such display:—I refer to
the celebrated attire of the pet slaves and belles affranchies of the old colonial days. A
full costume,—including violet or crimson "petticoat" of silk or satin; chemise with half-
sleeves, and much embroidery and lace; "trembling-pins" of gold (zépingue tremblant)
to attach the folds of the brilliant Madras turban; the great necklace of three or four
strings of gold beads bigger than peas (collier-choux); the ear-rings, immense but light
as egg-shells (zanneaux-à-clous or zanneaux-chenilles); the bracelets portes-bonheur);
the studs (boutons-à-clous); the brooches, not only for the turban, but for the
chemise, below the folds of the showy silken foulard or shoulder-scarf,—would
sometimes represent over five thousand francs expenditure. This gorgeous attire is
becoming less visible every year: it is now rarely worn except on very solemn
occasions,—weddings, baptisms, first communions, confirmations. The da (nurse) or
"porteuse-de-baptême" who bears the baby to church holds it at the baptismal font,
and afterwards carries it from house to house in order that all the friends of the family
may kiss it, is thus attired; but nowadays, unless she be a professional (for there are
professional das, hired only for such occasions), she usually borrows the jewellry. If
tall, young, graceful, with a rich gold tone of skin, the effect of her costume is dazzling
as that of a Byzantine Virgin. I saw one young da who, thus garbed, scarcely seemed
of the earth and earthly;—there was an Oriental something in her appearance difficult
to describe,—something that made you think of the Queen of Sheba going to visit
Solomon. She had brought a merchant's baby, just christened, to receive the caresses
of the family at whose house I was visiting; and when it came to my turn to kiss it, I
confess I could not notice the child: I saw only the beautiful dark face, coiffed with
orange and purple, bending over it, in an illumination of antique gold.... What a da!...
She represented really the type of that belle affranchie of other days, against whose
fascination special sumptuary laws were made; romantically she imaged for me the
supernatural god-mothers and Cinderellas of the creole fairy-tales. For these become
transformed in the West Indian folklore,—adapted to the environment, and to local
idealism:—Cinderella, for example, is changed to a beautiful metisse, wearing a
quadruple collier-choux, zépingues tremblants, and all the ornaments of a da.[38]
Recalling the impression of that dazzling da, I can even now feel the picturesque
justice of the fabulist's description of Cinderella's creole costume: Ça té ka baille ou
mal zie!—(it would have given you a pain in your eyes to look at her!)

... Even the every-day Martinique costume is slowly changing. Year by year the
"calendeuses"—the women who paint and fold the turbans—have less work to do;—
the colors of the douiellette are becoming less vivid;—while more and more young
colored girls are being élevées en chapeau ("brought up in a hat")—i.e., dressed and
educated like the daughters of the whites. These, it must be confessed, look far less
attractive in the latest Paris fashion, unless white as the whites themselves: on the
other hand, few white girls could look well in douillette and mouchoir,—not merely
because of color contrast, but because they have not that amplitude of limb and
particular cambering of the torso peculiar to the half-breed race, with its large bulk and
stature. Attractive as certain coolie women are, I observed that all who have adopted
the Martinique costume look badly in it: they are too slender of body to wear it to
advantage.
Slavery introduced these costumes, even though it probably did not invent them; and
they were necessarily doomed to pass away with the peculiar social conditions to
which they belonged. If the population clings still to its douillettes, mouchoirs, and
foulards, the fact is largely due to the cheapness of such attire. A girl can dress very
showily indeed for about twenty francs—shoes excepted;—and thousands never wear
shoes. But the fashion will no doubt have become cheaper and uglier within another
decade.
At the present time, however, the stranger might be sufficiently impressed by the
oddity and brilliancy of these dresses to ask about their origin,—in which case it is not
likely that he will obtain any satisfactory answer. After long research I found myself
obliged to give up all hope of being able to outline the history of Martinique costume,—
partly because books and histories are scanty or defective, and partly because such an
undertaking would require a knowledge possible only to a specialist. I found good
reason, nevertheless, to suppose that these costumes were in the beginning adopted
from certain fashions of provincial France,—that the respective fashions of Guadeloupe,
Martinique, and Cayenne were patterned after modes still worn in parts of the mother-
country. The old-time garb of the affranchie—that still worn by the da—somewhat
recalls dresses worn by the women of Southern France, more particularly about
Montpellier. Perhaps a specialist might also trace back the evolution of the various
creole coiffures to old forms of head-dresses which still survive among the French
country-fashions of the south and south-west provinces;—but local taste has so much
modified the original style as to leave it unrecognizable to those who have never
studied the subject. The Martinique fashion of folding and tying the Madras, and of
calendering it, are probably local; and I am assured that the designs of the curious
semi-barbaric jewellry were all invented in the colony, where the collier-choux is still
manufactured by local goldsmiths. Purchasers buy one, two, or three grains, or beads,
at a time, and string them only on obtaining the requisite number.... This is the sum of
all that I was able to learn on the matter; but in the course of searching various West
Indian authors and historians for information, I found something far more important
than the origin of the douillette or the collier-choux: the facts of that strange struggle
between nature and interest, between love and law, between prejudice and passion,
which forms the evolutional history of the mixed race.

[37] The brightly colored douillettes are classified by the people according to the designs of the printed
calico:—robe-à-bambou,—robe-à-bouquet,—robe-arc-en-ciel—robe-à-carreau,—etc., according as the
pattern is in stripes, flower-designs, "rainbow" bands of different tints, or plaidings. Ronde-en-ronde
means a stuff printed with disk-patterns, or link-patterns of different colors,—each joined with the other.
A robe of one color only is called a robe-uni.
The general laws of contrasts observed in the costume require the silk foulard, or shoulder-kerchief, to
make a sharp relief with the color of the robe, thus:—
Robe. Foulard.
Yellow Blue.
Dark Blue Yellow.
Pink Green.
Violet Bright red.
Red Violet.
Chocolate (cacao) Pale blue.
Sky blue Pale rose.

These refer, of course, to dominant or ground colors, as there are usually several tints in the foulard as
well as the robe. The painted Madras should always be bright yellow. According to popular ideas of good
dressing, the different tints of skin should be relieved by special choice of color in the robe, as follows:—
Capresse (a clear red skin) should wear Pale yellow.
Mulatresse (according to shade) {Rose.
{Blue.
{Green.
Négresse {White.
{Scarlet, or any violent color.
[38]"Vouèla Cendrillon evec yon bel ròbe velou grande lakhè.... Ça té ka bail ou mal ziè. Li té tini bel
zanneau dans zòreill li, quate-tou-chou, bouoche, bracelet, tremblant,—toutt sòte bel baggaïe conm
ça."...—(Conte Cendrillon,—d'après Turiault.)
—"There was Cendrillon with a beautiful long trailing robe of velvet on her!... It was enough to hurt
one's eyes to look at her! She had beautiful rings in her ears, and a collier-choux of four rows, brooches,
tremblants, bracelets,—everything fine of that sort."—(Story of Cinderella in Turinault's Creole
Grammar).

II

Considering only the French peasant colonist and the West African slave as the original
factors of that physical evolution visible in the modern fille-de-couleur, it would seem
incredible;—for the intercrossing alone could not adequately explain all the physical
results. To understand them fully, it will be necessary to bear in mind that both of the
original races became modified in their lineage to a surprising degree by conditions of
climate and environment.
The precise time of the first introduction of slaves into Martinique is not now possible
to ascertain,—no record exists on the subject; but it is probable that the establishment
of slavery was coincident with the settlement of the island. Most likely the first hundred
colonists from St. Christophe, who landed, in 1635, near the bay whereon the city of
St. Pierre is now situated, either brought slaves with them, or else were furnished with
negroes very soon after their arrival. In the time of Père Dutertre (who visited the
colonies in 1640, and printed his history of the French Antilles at Paris in 1667) slavery
was already a flourishing institution,—the foundation of the whole social structure.
According to the Dominican missionary, the Africans then in the colony were decidedly
repulsive; he describes the women as "hideous" (hideuses). There is no good reason to
charge Dutertre with prejudice in his pictures of them. No writer of the century was
more keenly sensitive to natural beauty than the author of that "Voyage aux Antilles"
which inspired Chateaubriand, and which still, after two hundred and fifty years,
delights even those perfectly familiar with the nature of the places and things spoken
of. No other writer and traveller of the period possessed to a more marked degree that
sense of generous pity which makes the unfortunate appear to us in an illusive, almost
ideal aspect. Nevertheless, he asserts that the negresses were, as a general rule,
revoltingly ugly,—and, although he had seen many strange sides of human nature
(having been a soldier before becoming a monk), was astonished to find that
miscegenation had already begun. Doubtless the first black women thus favored, or
afflicted, as the case might be, were of the finer types of negresses; for he notes
remarkable differences among the slaves procured from different coasts and various
tribes. Still, these were rather differences of ugliness than aught else: they were all
repulsive;—only some were more repulsive than others.[39] Granting that the first
mothers of mulattoes in the colony were the superior rather than the inferior physical
types,—which would be a perfectly natural supposition,—still we find their offspring
worthy in his eyes of no higher sentiment than pity. He writes in his chapter entitled
"De la naissance honteuse des mulastres":
—"They have something of their Father and something of their Mother,—in the same
wise that Mules partake of the qualities of the creatures that engendered them: for
they are neither all white, like the French; nor all black, like the Negroes, but have a
livid tint, which comes of both."...
To-day, however, the traveller would look in vain for a livid tint among the descendants
of those thus described: in less than two centuries and a half the physical
characteristics of the race have been totally changed. What most surprises is the
rapidity of the transformation. After the time of Père Labat, Europeans never could
"have mistaken little negro children for monkeys." Nature had begun to remodel the
white, the black, and half-breed according to environment and climate: the descendant
of the early colonists ceased to resemble his fathers; the creole negro improved upon
his progenitors;[40] the mulatto began to give evidence of those qualities of physical
and mental power which were afterwards to render him dangerous to the integrity of
the colony itself. In a temperate climate such a change would have been so gradual as
to escape observation for a long period;—in the tropics it was effected with a
quickness that astounds by its revelation of the natural forces at work.
—"Under the sun of the tropics," writes Dr. Rufz, of Martinique, "the African race, as
well as the European, becomes greatly modified in its reproduction. Either race gives
birth to a totally new being. The Creole African came into existence as did the Creole
white." And just as the offspring of Europeans who emigrated to the tropics from
different parts of France displayed characteristics so identical that it was impossible to
divine the original race-source,—so likewise the Creole negro—whether brought into
being by the heavy thick-set Congo, or the long slender black of Senegambia, or the
suppler and more active Mandingo,—appeared so remodelled, homogeneous, and
adapted in such wise to his environment that it was utterly impossible to discern in his
features anything of his parentage, his original kindred, his original source.... The
transformation is absolute. All that In be asserted is: "This is a white Creole; this is a
black Creole";—or, "This is a European white; this is an African black";—and
furthermore, after a certain number of years passed in the tropics, the enervated and
discolored aspect of the European may create uncertainty, as to his origin. But with
very few exceptions the primitive African, or, as he is termed here, the "Coast Black"
(le noir de la Côte), can be recognized at once....
... "The Creole negro is gracefully shaped, finely proportioned: his limbs are lithe, his
neck long;—his features are more delicate, his lips less thick, his nose less flattened,
than those of the African;—he has the Carib's large and melancholy eye, better
adapted to express the emotions.... Rarely can you discover in him the sombre fury of
the African, rarely a surly and savage mien: he is brave, chatty, boastful. His skin has
not the same tint as his father's,—it has become more satiny; his hair remains woolly,
but it is a finer wool... all his outlines are more rounded;—one may perceive that the
cellular tissue predominates, as in cultivated plants, of which the ligneous and savage
fibre has become transformed."...[41]
This new and comelier black race naturally won from its masters a more sympathetic
attention than could have been vouchsafed to its progenitors; and the consequences in
Martinique and elsewhere seemed to have evoked the curious Article 9 of the Code
Noir of 1665,—enacting, first, that free men who should have one or two children by
slave women, as well as the slave-owners permitting the same, should be each
condemned to pay two thousand pounds of sugar; secondly, that if the violator of the
ordinance should be himself the owner of the mother and father of her children, the
mother and the children should be confiscated for the profit of the Hospital, and
deprived for their lives of the right to enfranchisement. An exception, however, was
made to the effect that if the father were unmarried at the period of his concubinage,
he could escape the provisions of the penalty by marrying, "according to the rites of
the Church," the female slave, who would thereby be enfranchised, and her children
"rendered free and legitimate." Probably the legislators did not imagine that the first
portion of the article could prove inefficacious, or that any violator of the ordinance
would seek to escape the penalty by those means offered in the provision. The facts,
however, proved the reverse. Miscegenation continued; and Labat notices two cases of
marriage between whites and blacks,—describing the offspring of one union as "very
handsome little mulattoes." These legitimate unions were certainly exceptional,—one
of them was dissolved by the ridicule cast upon the father;—but illegitimate unions
would seem to have become common within a very brief time after the passage of the
law. At a later day they were to become customary. The Article 9 was evidently at
fault; and in March, 1724, the Black Code was reinforced by a new ordinance, of which
the sixth provision prohibited marriage as well as concubinage between the races.
It appears to have had no more effect than the previous law, even in Martinique,
where the state of public morals was better than in Santo Domingo. The slave race had
begun to exercise an influence never anticipated by legislators. Scarcely a century had
elapsed since the colonization of the island; but in that time climate and civilization had
transfigured the black woman. "After one or two generations," writes the historian
Rufz, "the Africaine, reformed, refined, beautified in her descendants, transformed into
the creole negress, commenced to exert a fascination irresistible, capable of winning
anything (capable de tout obtenir)."[42] Travellers of the eighteenth century were
confounded by the luxury of dress and of jewellry displayed by swarthy beauties in St.
Pierre. It was a public scandal to European eyes. But the creole negress or mulattress,
beginning to understand her power, sought for higher favors and privileges than silken
robes and necklaces of gold beads: she sought to obtain, not merely liberty for herself,
but for her parents, brothers, sisters,—even friends. What successes she achieved in
this regard may be imagined from the serious statement of creole historians that if
human nature had been left untrammelled to follow its better impulses, slavery would
have ceased to exist a century before the actual period of emancipation! By 1738,
when the white population had reached its maximum (15,000),[43] and colonial luxury
had arrived at its greatest height, the question of voluntary enfranchisement was
becoming very grave. So omnipotent the charm of half-breed beauty that masters were
becoming the slaves of their slaves. It was not only the creole negress who had
appeared to play a part in this strange drama which was the triumph of nature over
interest and judgment: her daughters, far more beautiful, had grown up to aid her, and
to form a special class. These women, whose tints of skin rivalled the colors of ripe
fruit, and whose gracefulness—peculiar, exotic, and irresistible—made them formidable
rivals to the daughters of the dominant race, were no doubt physically superior to the
modern filles-de-couleur. They were results of a natural selection which could have
taken place in no community otherwise constituted;—the offspring of the union
between the finer types of both races. But that which only slavery could have rendered
possible began to endanger the integrity of slavery itself: the institutions upon which
the whole social structure rested were being steadily sapped by the influence of half-
breed girls. Some new, severe, extreme policy was evidently necessary to avert the
already visible peril. Special laws were passed by the Home-Government to check
enfranchisement, to limit its reasons or motives; and the power of the slave woman
was so well comprehended by the Métropole that an extraordinary enactment was
made against it. It was decreed that whosoever should free a woman of color would
have to pay to the Government three times her value as a slave!
Thus heavily weighted, emancipation advanced much more slowly than before, but it
still continued to a considerable extent. The poorer creole planter or merchant might
find it impossible to obey the impulse of his conscience or of his affection, but among
the richer classes pecuniary considerations could scarcely affect enfranchisement. The
country had grown wealthy; and although the acquisition of wealth may not evoke
generosity in particular natures, the enrichment of a whole class develops pre-existing
tendencies to kindness, and opens new ways for its exercise. Later in the eighteenth
century, when hospitality had been cultivated as a gentleman's duty to fantastical
extremes,—when liberality was the rule throughout society,—when a notary summoned
to draw up a deed, or a priest invited to celebrate a marriage, might receive for fee
five thousand francs in gold,—there were certainly many emancipations.... "Even
though interest and public opinion in the colonies," says a historian,[44] "were adverse
to enfranchisement, the private feeling of each man combated that opinion;—Nature
resumed her sway in the secret places of hearts;—and as local custom permitted a sort
of polygamy, the rich man naturally felt himself bound in honor to secure the freedom
of his own blood.... It was not a rare thing to see legitimate wives taking care of the
natural children of their husbands,—becoming their godmothers (s'en faire les
marraines)."... Nature seemed to laugh all these laws to scorn, and the prejudices of
race! In vain did the wisdom of legislators attempt to render the condition of the
enfranchised more humble,—enacting extravagant penalties for the blow by which a
mulatto might avenge the insult of a white,—prohibiting the freed from wearing the
same dress as their former masters or mistresses wore;—"the belles affranchies found,
in a costume whereof the negligence seemed a very inspiration of voluptuousness,
means of evading that social inferiority which the law sought to impose upon them:—
they began to inspire the most violent jealousies."[45]

[39]It is quite possible, however, that the slaves of Dutertre's time belonged for the most part to the
uglier African tribes; and that later supplies may have been procured from other parts of the slave coast.
Writing half a century later, Père Labat declares having seen freshly disembarked blacks handsome
enough to inspire an artist:—"J'en ai vu des deux sexes faits à peindre, et beaux par merveille" (vol. iv.
chap, vii,). He adds that their skin was extremely fine, and of velvety softness;—"le velours n'est pas
plus doux."... Among the 30,000 blacks yearly shipped to the French colonies, there were doubtless
many representatives of the finer African races.
[40]"Leur sueur n'est pas fétide comme celle des nègres de la Guinée," writes the traveller Dauxion-
Lavaysse, in 1813.
[41]Dr. E. Rufz: "Études historiques et statistiques sur la population de la Martinique." St. Pierre: 1850.
Vol. I, pp. 148-50.
It has been generally imagined that the physical constitution of the black race was proof against the
deadly climate of the West Indies. The truth is that the freshly imported Africans died of fever by
thousands and tens-of-thousands;—the creole-negro race, now so prolific, represents only the fittest
survivors in the long and terrible struggle of the slave element to adapt itself to the new environment.
Thirty thousand negroes a year were long needed to supply the French colonies. Between 1700 and
1789 no less than 900,000 slaves were imported by San Domingo alone;—yet there were less than half
that number left in 1789. (See Placide Justin's history of Santo Domingo, p. 147.) The entire slave
population of Barbadoes had to be renewed every sixteen years, according to estimates: the loss to
planters by deaths of slaves (reckoning the value of a slave at only £20 sterling) during the same period
was £1,600,000 ($8,000,000). (Burck's "History of European Colonies," vol. II., p. 141; French edition of
1767.)
[42]Rufz: "Études," vol. I., p. 236.
[43]I am assured it has now fallen to a figure not exceeding 5000.
[44]Rufz: "Études," vol. II., pp. 311, 312.
[45]Rufz: "Études," vol. I., p. 237.
III

What the legislators of 1685 and 1724 endeavored to correct did not greatly improve
with the abolition of slavery, nor yet with those political troubles which socially
deranged colonial life. The fille-de-couleur, inheriting the charm of the belle affranchie,
continued to exert a similar influence, and to fulfil an almost similar destiny. The
latitude of morals persisted,—though with less ostentation: it has latterly contracted
under the pressure of necessity rather than through any other influences. Certain
ethical principles thought essential to social integrity elsewhere have always been
largely relaxed in the tropics; and—excepting, perhaps, Santo Domingo—the moral
standard in Martinique was not higher than in the other French colonies. Outward
decorum might be to some degree maintained; but there was no great restraint of any
sort upon private lives: it was not uncommon for a rich man to have many "natural"
families; and almost every individual of means had children of color. The superficial
character of race prejudices was everywhere manifested by unions, which although
never mentioned in polite converse, were none the less universally known; and the
"irresistible fascination" of the half-breed gave the open lie to pretended hate. Nature,
in the guise of the belle affranchie, had mocked at slave codes;—in the fille-de-couleur
she still laughed at race pretensions, and ridiculed the fable of physical degradation.
To-day, the situation has not greatly changed; and with such examples on the part of
the cultivated race, what could be expected from the other? Marriages are rare;—it has
been officially stated that the illegitimate births are sixty per cent; but seventy-five to
eighty per cent would probably be nearer the truth. It is very common to see in the
local papers such announcements as: Enfants légitimes, 1 (one birth announced);
enfants naturels, 25.
In speaking of the fille-de-couleur it is necessary also to speak of the extraordinary
social stratification of the community to which she belongs. The official statement of
20,000 "colored" to the total population of between 173,000 and 174,000 (in which the
number of pure whites is said to have fallen as low as 5,000) does not at all indicate
the real proportion of mixed blood. Only a small element of unmixed African descent
really exists; yet when a white creole speaks of the gens-de-couleur he certainly
means nothing darker than a mulatto skin. Race classifications have been locally made
by sentiments of political origin: at least four or five shades of visible color are classed
as negro. There is, however, some natural truth at the bottom of this classification:
where African blood predominates, the sympathies are likely to be African; and the
turning-point is reached only in the true mulatto, where, allowing the proportions of
mixed blood to be nearly equal, the white would have the dominant influence in
situations more natural than existing politics. And in speaking of the filles-de-couleur,
the local reference is always to women in whom the predominant element is white: a
white creole, as a general rule, deigns only thus to distinguish those who are nearly
white,—more usually he refers to the whole class as mulattresses. Those women
whom wealth and education have placed in a social position parallel with that of the
daughters of creole whites are in some cases allowed to pass for white,—or at the very
worst, are only referred to in a whisper as being de couleur. (Needless to say, these
are totally beyond the range of the present considerations: there is nothing to be
further said of them except that they can be classed with the most attractive and
refined women of the entire tropical world.) As there is an almost infinite gradation
from the true black up to the brightest sang-mêlé, it is impossible to establish any
color-classification recognizable by the eye alone; and whatever lines of demarcation
can be drawn between castes must be social rather than ethnical. In this sense we
may accept the local Creole definition of fille-de-couleur as signifying, not so much a
daughter of the race of visible color, as the half-breed girl destined from her birth to a
career like that of the belle affranchie of the old regime;—for the moral cruelties of
slavery have survived emancipation.
Physically, the typical fille-de-couleur may certainly be classed, as white creole writers
have not hesitated to class her, with the "most beautiful women of the human race."
[46] She has inherited not only the finer bodily characteristics of either parent race, but
a something else belonging originally to neither, and created by special climatic and
physical conditions,—a grace, a suppleness of form, a delicacy of extremities (so that
all the lines described by the bending of limbs or fingers are parts of clean curves), a
satiny smoothness and fruit-tint of skin,—solely West Indian.... Morally, of course, it is
much more difficult to describe her; and whatever may safely be said refers rather to
the fille-de-couleur of the past than of the present half-century. The race is now in a
period of transition: public education and political changes are modifying the type, and
it is impossible to guess the ultimate consequence, because it is impossible to safely
predict what new influences may yet be brought to affect its social development.
Befare the present era of colonial decadence, the character of the fille-de-couleur was
not what it is now. Even when totally uneducated, she had a peculiar charm,—that
charm of childishness which has power to win sympathy from the rudest natures. One
could not but feel attracted towards this naïf being, docile as an infant, and as easily
pleased or as easily pained,—artless in her goodnesses as in her faults, to all outward
appearance;—willing to give her youth, her beauty, her caresses to some one in
exchange for the promise to love her,—perhaps also to care for a mother, or a younger
brother. Her astonishing capacity for being delighted with trifles, her pretty vanities and
pretty follies, her sudden veerings of mood from laughter to tears,—like the sudden
rainbursts and sunbursts of her own passionate climate: these touched, drew, won,
and tyrannized. Yet such easily created joys and pains did not really indicate any deep
reserve of feeling: rather a superficial sensitiveness only,—like the zhèbe-m'amisé, or
zhèbe-manmzelle, whose leaves close at the touch of a hair. Such human
manifestations, nevertheless, are apt to attract more in proportion as they are more
visible,—in proportion as the soul-current, being less profound, flows more audibly. But
no hasty observation could have revealed the whole character of the fille-de-couleur to
the stranger, equally charmed and surprised: the creole comprehended her better, and
probably treated her with even more real kindness. The truth was that centuries of
deprivation of natural rights and hopes had given to her race—itself fathered by
passion unrestrained and mothered by subjection unlimited—an inherent scepticism in
the duration of love, and a marvellous capacity for accepting the destiny of
abandonment as one accepts the natural and the inevitable. And that desire to please
—which in the fille-de-couleur seemed to prevail above all other motives of action
(maternal affection excepted)—could have appeared absolutely natural only to those
who never reflected that even sentiment had been artificially cultivated by slavery.
She asked for so little,—accepted a gift with such childish pleasure,—submitted so
unresistingly to the will of the man who promised to love her. She bore him children—
such beautiful children!—whom he rarely acknowledged, and was never asked to
legitimatize;—and she did not ask perpetual affection notwithstanding,—regarded the
relation as a necessarily temporary one, to be sooner or later dissolved by the
marriage of her children's father. If deceived in all things,—if absolutely ill-treated and
left destitute, she did not lose faith in human nature: she seemed a born optimist,
believing most men good;—she would make a home for another and serve him better
than any slave.... "Née de l'amour," says a creole writer, "la fille-de-couleur vit d'amour,
de rires, et d'oublis."...[47]
Then came the general colonial crash!... You cannot see its results without feeling
touched by them. Everywhere the weird beauty, the immense melancholy of tropic
ruin. Magnificent terraces, once golden with cane, now abandoned to weeds and
serpents;—deserted plantation-homes, with trees rooted in the apartments and
pushing up through the place of the roofs;—grass-grown alleys ravined by rains;—fruit-
trees strangled by lianas;—here and there the stem of some splendid palmiste, brutally
decapitated, naked as a mast;—petty frail growths of banana-trees or of bamboo
slowly taking the place of century-old forest giants destroyed to make charcoal. But
beauty enough remains to tell what the sensual paradise of the old days must have
been, when sugar was selling at 52.
And the fille-de-couleur has also changed. She is much less humble and submissive,—
somewhat more exacting: she comprehends better the moral injustice of her position.
The almost extreme physical refinement and delicacy, bequeathed to her by the
freedwomen of the old regime, are passing away: like a conservatory plant deprived of
its shelter, she is returning to a more primitive condition,—hardening and growing
perhaps less comely as well as less helpless. She perceives also in a vague way the
peril of her race: the creole white, her lover and protector, is emigrating;—the
domination of the black becomes more and more probable. Furthermore, with the
continual increase of the difficulty of living, and the growing pressure of population,
social cruelties and hatreds have been developed such as her ancestors never knew.
She is still loved; but it is alleged that she rarely loves the white, no matter how large
the sacrifices made for her sake, and she no longer enjoys that reputation of fidelity
accorded to her class in other years. Probably the truth is that the fille-de-couleur
never had at any time capacity to bestow that quality of affection imagined or exacted
as a right. Her moral side is still half savage: her feelings are still those of a child. If
she does not love the white man according to his unreasonable desire, it is certain at
least that she loves him as well as he deserves. Her alleged demoralization is more
apparent than real;—she is changing from an artificial to a very natural being, and
revealing more and more in her sufferings the true character of the luxurious social
condition that brought her into existence. As a general rule, even while questioning her
fidelity, the creole freely confesses her kindness of heart, and grants her capable of
extreme generosity and devotedness to strangers or to children whom she has an
opportunity to care for. Indeed, her natural kindness is so strikingly in contrast with the
harder and subtler character of the men of color that one might almost feel tempted to
doubt if she belong to the same race. Said a creole once, in my hearing:—"The gens-
de-couleur are just like the tourtouroux:[48] one must pick out the females and leave
the males alone." Although perhaps capable of a double meaning, his words were not
lightly uttered;—he referred to the curious but indubitable fact that the character of
the colored woman appears in many respects far superior to that of the colored man.
In order to understand this, one must bear in mind the difference in the colonial
history of both sexes; and a citation from General Romanet,[49] who visited Martinique
at the end of the last century, offers a clue to the mystery. Speaking of the tax upon
enfranchisement, he writes:—
—"The governor appointed by the sovereign delivers the certificates of liberty,—on
payment by the master of a sum usually equivalent to the value of the subject. Public
interest frequently justifies him in making the price of the slave proportionate to the
desire or the interest manifested by the master. It can be readily understood that the
tax upon the liberty of the women ought to be higher than that of the men: the latter
unfortunates having no greater advantage than that of being useful;—the former know
how to please: they have those rights and privileges which the whole world allows to
their sex; they know how to make even the fetters of slavery serve them for
adornments. They may be seen placing upon their proud tyrants the same chains worn
by themselves, and making them kiss the marks left thereby: the master becomes the
slave, and purchases another's liberty only to lose his own."
Long before the time of General Romanet, the colored male slave might win liberty as
the guerdon of bravery in fighting against foreign invasion, or might purchase it by
extraordinary economy, while working as a mechanic on extra time for his own account
(he always refused to labor with negroes); but in either case his success depended
upon the possession and exercise of qualities the reverse of amiable. On the other
hand, the bondwoman won manumission chiefly through her power to excite affection.
In the survival and perpetuation of the fittest of both sexes these widely different
characteristics would obtain more and more definition with successive generations.
I find in the "Bulletin des Actes Administratifs de la Martinique" for 1831 (No. 41) a list
of slaves to whom liberty was accorded pour services rendus à leurs maîtres. Out of
the sixty-nine enfranchisements recorded under this head, there are only two names of
male adults to be found,—one an old man of sixty;—the other, called Laurencin, the
betrayer of a conspiracy. The rest are young girls, or young mothers and children;—
plenty of those singular and pretty names in vogue among the creole population,—
Acélie, Avrillette, Mélie, Robertine, Célianne, Francillette, Adée, Catharinette, Sidollie,
Céline, Coraline;—and the ages given are from sixteen to twenty-one, with few
exceptions. Yet these liberties were asked for and granted at a time when Louis
Philippe had abolished the tax on manumissions.... The same "Bulletin" contains a list
of liberties granted to colored men, pour service accompli dans la milice, only!
Most of the French West Indian writers whose works I was able to obtain and examine
speak severely of the hommes-de-couleur as a class,—in some instances the historian
writes with a very violence of hatred. As far back as the commencement of the
eighteenth century, Labat, who, with all his personal oddities, was undoubtedly a fine
judge of men, declared:—"The mulattoes are as a general rule well made, of good
stature, vigorous, strong, adroit, industrious, and daring (hardis) beyond all
conception. They have much vivacity, but are given to their pleasures, fickle, proud,
deceitful (cachés), wicked, and capable of the greatest crimes." A San Domingo
historian, far more prejudiced than Père Labat, speaks of them "as physically superior,
though morally inferior to the whites": he wrote at a time when the race had given to
the world the two best swordsmen it has yet perhaps seen,—Saint-Georges and Jean-
Louis.
Commenting on the judgment of Père Labat, the historian Borde observes:—"The
wickedness spoken of by Père Labat doubtless relates to their political passions only;
for the women of color are, beyond any question, the best and sweetest persons in the
world—à coup sûr, les meilleures et les plus douces personnes qu'il y ait au monde."—
("Histoire de l'Ile de la Trinidad," par M. Pierre Gustave Louis Borde, vol. I., p. 222.)
The same author, speaking of their goodness of heart, generosity to strangers and the
sick says "they are born Sisters of Charity";—and he is not the only historian who has
expressed such admiration of their moral qualities. What I myself saw during the
epidemic of 1887-88 at Martinique convinced me that these eulogies of the women of
color are not extravagant. On the other hand, the existing creole opinion of the men of
color is much less favorable than even that expressed by Père Labat. Political events
and passions have, perhaps, rendered a just estimate of their qualities difficult. The
history of the hommes-de-couleur in all the French colonies has been the same;—
distrusted by the whites, who feared their aspirations to social equality, distrusted even
more by the blacks (who still hate them secretly, although ruled by them), the
mulattoes became an Ishmaelitish clan, inimical to both races, and dreaded of both. In
Martinique it was attempted, with some success, to manage them by according
freedom to all who would serve in the militia for a certain period with credit. At no time
was it found possible to compel them to work with blacks; and they formed the whole
class of skilled city workmen and mechanics for a century prior to emancipation.
... To-day it cannot be truly said of the fille-de-couleur that her existence is made up of
"love, laughter, and forgettings." She has aims in life,—the bettering of her condition,
the higher education of her children, whom she hopes to free from the curse of
prejudice. She still clings to the white, because through him she may hope to improve
her position. Under other conditions she might even hope to effect some sort of
reconciliation between the races. But the gulf has become so much widened within the
last forty years, that no rapprochement now appears possible; and it is perhaps too
late even to restore the lost prosperity of the colony by any legislative or commercial
reforms. The universal creole belief is summed up in the daily-repeated cry: "C'est un
pays perdu!" Yearly the number of failures increase; and more whites emigrate;—and
with every bankruptcy or departure some fille-de-couleur is left almost destitute, to
begin life over again. Many a one has been rich and poor several times in succession;—
one day her property is seized for debt;—perhaps on the morrow she finds some one
able and willing to give her a home again... Whatever comes, she does not die for
grief, this daughter of the sun: she pours out her pain in song, like a bird, Here is one
of her little improvisations,—a song very popular in both Martinique and Guadeloupe,
though originally composed in the latter colony:—
—"Good-bye Madras!
Good-bye foulard!
Good-bye pretty calicoes!
Good-bye collier-choux!
That ship
Which is there on the buoy,
It is taking
My doudoux away."
—"Adiéu Madras!
Adiéu foulard!
Adiéu dézinde!
Adiéu collier-choux!
Batiment-là
Qui sou labouè-là,
Li ka mennein
Doudoux-à-moin allé."
—"Very good-day,—
Monsieur the Consignee.
I come
To make one little petition.
My doudoux
Is going away.
Alas! I pray you
Delay his going."
—"Bien le-bonjou',
Missié le Consignataire.
Moin ka vini
Fai yon ti pétition;
Doudoux-à-moin
Y ka pati,—T'enprie, hélas!
Rétàdé li."
[He answers kindly in French: the békés are always kind to these gentle children.]
—"My dear child,
It is too late.
The bills of lading
Are already signed;
The ship
Is already on the buoy.
In an hour from now
They will be getting her under way."
—"Ma chère enfant
Il est trop tard,
Les connaissements
Sont déjà signés,
Est déjà sur la bouée;
Dans une heure d'ici,
Ils vont appareiller."
—"When the foulards came....
I always had some;
When the Madras-kerchiefs came,
I always had some;
When the printed calicoes came,
I always had some.
... That second officer—Is such a kind man!"
—"Foulard rivé,
Moin té toujou tini;
Madras rivé,
Moin té toujou tini;
Dézindes rivé,
Moin té toujou tini.—Capitaine sougonde
C'est yon bon gàçon!"
"Everybody has
Somebody to love;
Everybody has
Somebody to pet;
Every body has
A sweetheart of her own.
I am the only one
Who cannot have that,—I!"
"Toutt moune tini
Yon moune yo aimé;
Toutt moune tini
Yon moune yo chéri;
Toutt moune tini
Yon doudoux à yo.
Jusse moin tou sèle
Pa tini ça—moin!"
... On the eve of the Fête Dieu, or Corpus Christi festival, in all these Catholic
countries, the city streets are hung with banners and decorated with festoons and with
palm branches; and great altars are erected at various points along the route of the
procession, to serve as resting-places for the Host. These are called reposoirs; in creole
patois, "reposouè Bon-Dié." Each wealthy man lends something to help to make them
attractive,—rich plate, dainty crystal, bronzes, paintings, beautiful models of ships or
steamers, curiosities from remote parts of the world.... The procession over, the altar is
stripped, the valuables are returned to their owners: all the splendor disappears.... And
the spectacle of that evanescent magnificence, repeated year by year, suggested to
this proverb-loving people a similitude for the unstable fortune of the fille-de-couleur:—
Fortune milatresse c'est reposouè Bon-Dié. (The luck of the mulattress is the resting-
place of the Good-God).

[46]La race de sang-mêlé, issue des blancs et des noirs, est éminement civilizable. Comme types
physiques, elle fournit dans beaucoup d'individus, dans ses femmes en général, les plus beaux
specimens de la race humaine.—"Le Préjugé de Race aux Antilles Françaises." Par G. Souquet-Basiège.
St. Pierre, Martinique: 1883. pp. 661-62.
[47]Turiault: "Étude sur le langage Créole de la Martinique." Brest: 1874.... On page 136 he cites the
following pretty verses in speaking of the fille-de-couleur:—
L'Amour prit soin de la former
Tendre, naïve, et caressante.
Faite pour plaire, encore plus pour aimer.
Portant tous les traits précieux
Du caractère d'une amante.
Le plaisir sur sa bouche et l'amour dans set yeux.
[48]A sort of land-crab;—the female is selected for food, and, properly cooked, makes a delicious dish;—
the male is almost worthless.
[49]"Voyage à la Martinique," Par J. R., Général de Brigade. Paris: An. XII., 1804. Page 106.
BÊTE-NI-PIÉ

St. Pierre is in one respect fortunate beyond many tropical cities;—she has
scarcely any mosquitoes, although there are plenty of mosquitoes in other
parts of Martinique, even in the higher mountain villages. The flood of bright
water that pours perpetually through all her streets, renders her
comparatively free from the pest;—nobody sleeps under a mosquito bar.
Nevertheless, St. Pierre is not exempt from other peculiar plagues of tropical
life; and you cannot be too careful about examining your bed before
venturing to lie down, and your clothing before you dress;—for various
disagreeable things might be hiding in them: a spider large as a big crab, or a
scorpion or a mabouya or a centipede,—or certain large ants whose bite
burns like the pricking of a red-hot needle. No one who has lived in St. Pierre
is likely to forget the ants.... There are three or four kinds in every house;—
the fourmi fou (mad ant), a little speckled yellowish creature whose
movements are so rapid as to delude the vision; the great black ant which
allows itself to be killed before it lets go what it has bitten; the venomous little red ant,
which is almost too small to see; and the small black ant which does not bite at all,—
are usually omnipresent, and appear to dwell together in harmony. They are pests in
kitchens, cupboards, and safes; but they are scavengers. It is marvellous to see them
carrying away the body of a great dead roach or centipede,—pulling and pushing
together like trained laborers, and guiding the corpse over obstacles or around them
with extraordinary skill.... There was a time when ants almost destroyed the colony,—
in 1751. The plantations, devastated by them are described by historians as having
looked as if desolated by fire. Underneath the ground in certain places, layers of their
eggs two inches deep were found extending over acres. Infants left unwatched in the
cradle for a few hours were devoured alive by them. Immense balls of living ants were
washed ashore at the same time on various parts of the coast (a phenomenon
repeated within the memory of creoles now living in the north-east parishes). The
Government vainly offered rewards for the best means of destroying the insects; but
the plague gradually disappeared as it came.
None of these creatures can be prevented from entering a dwelling;—you may as well
resign yourself to the certainty of meeting with them from time to time. The great
spiders (with the exception of those which are hairy) need excite no alarm or disgust;
—indeed they are suffered to live unmolested in many houses, partly owing to a belief
that they bring good-luck, and partly because they destroy multitudes of those
enormous and noisome roaches which spoil whatever they cannot eat. The scorpion is
less common; but it has a detestable habit of lurking under beds; and its bite
communicates a burning fever. With far less reason, the mabouya is almost equally
feared. It is a little lizard about six inches long, and ashen-colored;—it haunts only the
interior of houses, while the bright-green lizards dwell only upon the roofs. Like other
reptiles of the same order, the mabouya can run over or cling to polished surfaces; and
there is a popular belief that if frightened, it will leap at one's face or hands and there
fasten itself so tightly that it cannot be dislodged except by cutting it to pieces.
Moreover, it's feet are supposed to have the power of leaving certain livid and
ineffaceable marks upon the skin of the person to whom it attaches itself:—ça ka ba ou
lota, say the colored people. Nevertheless, there is no creature more timid and
harmless than the mabouya.
But the most dreaded and the most insolent invader of domestic peace is the
centipede. The water system of the city banished the mosquito; but it introduced the
centipede into almost every dwelling. St. Pierre has a plague of centipedes. All the
covered drains, the gutters, the crevices of fountain-basins and bathing-basins, the
spaces between floor and ground, shelter centipedes. And the bête à-mille-pattes is
the terror of the barefooted population:—scarcely a day passes that some child or
bonne or workman is not bitten by the creature.
The sight of a full-grown centipede is enough to affect a strong set of nerves. Ten to
eleven inches is the average length of adults; but extraordinary individuals much
exceeding this dimension may be sometimes observed in the neighborhood of
distilleries (rhommeries) and sugar-refineries. According to age, the color of the
creature varies from yellowish to black;—the younger ones often have several different
tints; the old ones are uniformly jet-black, and have a carapace of surprising
toughness,—difficult to break. If you tread, by accident or design, upon the tail, the
poisonous head will instantly curl back and bite the foot through any ordinary thickness
of upper-leather.
As a general rule the centipede lurks about the court-yards, foundations, and drains by
preference; but in the season of heavy rains he does not hesitate to move upstairs,
and make himself at home in parlors and bed-rooms. He has a provoking habit of
nestling in your moresques or your chinoises,—those wide light garments you put on
before taking your siesta or retiring for the night. He also likes to get into your
umbrella,—an article indispensable in the tropics; and you had better never open it
carelessly. He may even take a notion to curl himself up in your hat, suspended on the
wall. (I have known a trigonocephalus to do the same thing in a country-house). He
has also a singular custom of mounting upon the long trailing dresses (douillettes)
worn by Martinique women,—and climbing up very swiftly and lightly to the wearer's
neck, where the prickling of his feet first betrays his presence. Sometimes he will get
into bed with you and bite you, because you have not resolution enough to lie perfectly
still while he is tickling you.... It is well to remember before dressing that merely
shaking a garment may not dislodge him;—you must examine every part very
patiently,—particularly the sleeves of a coat and the legs of pantaloons.
The vitality of the creature is amazing. I kept one in a bottle without food or water for
thirteen weeks, at the end of which time it remained active and dangerous as ever.
Then I fed it with living insects, which it devoured ravenously;—beetles, roaches,
earthworms, several lepismaoe, even one of the dangerous-looking millepedes, which
have a great resemblance in outward structure to the centipede, but a thinner body,
and more numerous limbs,—all seemed equally palatable to the prisoner.... I knew an
instance of one, nearly a foot long, remaining in a silk parasol for more than four
months, and emerging unexpectedly one day, with aggressiveness undiminished, to
bite the hand that had involuntarily given it deliverance.
In the city the centipede has but one natural enemy able to cope with him,—the hen!
The hen attacks him with delight, and often swallows him, head first, without taking
the trouble to kill him. The cat hunts him, but she is careful never to put her head near
him;—she has a trick of whirling him round and round upon the floor so quickly as to
stupefy him: then, when she sees a good chance, she strikes him dead with her claws.
But if you are fond of your cat you will let her run no risks, as the bite of a large
centipede might have very bad results for your pet. Its quickness of movement
demands all the quickness of even the cat for self-defence.... I know of men who have
proved themselves able to seize a fer-de-lance by the tail, whirl it round and round,
and then flip it as you would crack a whip,—whereupon the terrible head flies off; but I
never heard of anyone in Martinique daring to handle a living centipede.
There are superstitions concerning the creature which have a good effect in
diminishing his tribe. If you kill a centipede, you are sure to receive money soon; and
even if you dream of killing one it is good-luck. Consequently, people are glad of any
chance to kill centipedes,—usually taking a heavy stone or some iron utensil for the
work;—a wooden stick is not a good weapon. There is always a little excitement when
a bête-ni-pié (as the centipede is termed in the patois) exposes itself to death; and you
may often hear those who kill it uttering a sort of litany of abuse with every blow, as if
addressing a human enemy:—"Quitté moin tchoué ou, maudi!—quitté moin tchoué ou,
scelerat!—quitté moin tchoué ou, Satan!—quitté moin tchoué ou, abonocio!" etc. (Let
me kill you, accursed! scoundrel! Satan! abomination!)
The patois term for the centipede is not a mere corruption of the French bête-à-mille-
pattes. Among a population of slaves, unable to read or write,[50] there were only the
vaguest conceptions of numerical values; and the French term bête-à-mille-pattes was
not one which could appeal to negro imagination. The slaves themselves invented an
equally vivid name, bête-anni-pié (the Beast-which-is-all-feet); anni in creole signifying
"only," and in such a sense "all." Abbreviated by subsequent usage to bête-'ni-pié, the
appellation has amphibology;—for there are two words ni in the patois, one signifying
"to have," and the other "naked." So that the creole for a centipede might be
translated in three ways,—"the Beast-which-is-all-feet"; or, "the Naked-footed Beast";
or, with fine irony of affirmation, "the Beast-which-has-feet."

[50]According to the Martinique "Annuaire" for 1887, there were even then, out of a total population of
173,182, no less than 125,366 unable to read and write.

II
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like