Let's say that we wanted to list the territories and
the armed forces, right along with the other states in alphabetical order.
We'll add a new file named combined_sort.
We'll start by creating a master array of all the options.
We'll use the array merge function to merge each of the files we want to use.
Then we'll use the file function to retrieve each line as a separate
item in an array.
I'm going to add an option to the file function,
that tells the function to ignore the new line characters.
This will trim the new line characters from each of our elements, so
that we can keep things clean, and only add line breaks where we specify.
Territories, And armed forces.
Next, I want to sort these items.
But I want to sort them by the display name,
without looking at any of the HTML tags.
I'm going to create a function to compare the values without tags.
CompareStrings.
We pass the strings we're going to compare,
And then we use the string case compare.
This is a binary safe case-insensitive string comparison.
Then we can use the strip_tags function, On both our values.
This will just leave the display text to compare.
We can then return these results.
Now I can use the user sort function, usort, we pass the array states,
and then we pass the function that we want to use, compareStrings.
This will sort our states array, using our compareStrings function.
Now that our array is ready to go,
we can write it directly to a file using the file_put_contents.
File_put_contents uses the same write mode that we used in the last file with fopen,
but we can also specify a file append flag if we prefer to add the contents
to the end of an existing file.
We use implode to join our array as a string,
and use PHP_EOL as the separator.
This will give us a nice line break between each option.
Let's add a select, and include this new file so
that we can preview it in the browser.
Let's use sorted instead of combined.
Then it won't overwrite the other file.
Now I have a dropdown that includes states, territories, and armed forces,
all in alphabetical order.
There are a lot more functions, feature, and options when it comes to reading and
writing files.
But until you're actually going to use them, they won't do you much good.
Scan through the documentation to get an idea of what is available, so
that when you do need to use it, you're ready.
Now that you know the basics of reading and
writing files with PHP, let's add a parsing component in the next section.
We'll use some of the most common data types, and show how PHP
can parse those files to create a data driven, personal recommendation site.