Anda di halaman 1dari 2135

Learn Web Development with Vegibit!

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools
and many iterations to get reader feedback, pivot until you have the right book and build
traction once you do. This book is for sale at the following url:
https://leanpub.com/learnwebdevelopmentwithvegibit

Please Share Or Link To This Book!


Thanks for checking out this book, Please share or link to this book to help us reach more readers!

Read Learn Web Development with Vegibit

Read Learn Web Development With Vegibit

Read Learn Web Development With Vegibit

<iframe width="160" height="400" src="https://leanpub.com/learnwebdevelopmentwithvegibit/embed" frameborder="0"


allowtransparency="true"></iframe>

General Table of Contents


Chapter 1: HTML
Chapter 2: PHP
Chapter 3: MySQL
Chapter 4: JavaScript
Chapter 5: WordPress
Chapter 6: Laravel
Chapter 7: Object Oriented Programming
Chapter 8: Linux
Chapter 9: Virtualization
Winnie!
Puppies keep us sane in an insane world ☺

Chapter 1: HTML
What Is HTML

We’re going to take a close look now at HTML5 and in order to do that, we have
to take a look at a little bit about what HTML is, where it comes from, and the
direction it is headed. HTML truly is the language of the web. I know we have
spoken about JavaScript being the language of the web, or PHP being the
language of the web. In fact, there are many languages of the web, but when it
comes right down to it, none of the others really matters if you do not have
HTML first. HTML is really the enabler of the World Wide Web. So let’s dig right
in and get our hands dirty with some HTML!

Hypertext Markup Language


HTML is an acronym for Hypertext Markup Language. The Hypertext portion of HTML is
what refers to the ability of this technology to create links to other websites, webpages, or
resources. It is the part of the web that well, give us a web! It is due to the ability to be able
to create an anchor tag that the world wide web exists as it does today. It is a very simply
yet amazingly powerful concept, and the biggest businesses in the world make use of this
technology everyday to move ideas forward. An entire industry exists around this concept,
and search engines like Google and Bing tirelessly study the relationships between links to
provide results to users that complete searches on their websites. The Markup of HTML is
the other concept within HTML, and it is via the markup that we have formatted text,
images, and various other resources embedded within web pages.

Key HTML Concepts


• Originally based on SGML The precursor to HTML is a markup language called
SGML, or Standard Generalized Markup Language.
• Hyperlinks are what power the modern Web Often we take links for granted these
days, but they are the vital component of the web.
• Several Versions of HTML in use Quicks Mode, HTML 2.0, HTML 3.2, HTML 4.01,
HTML5. All of the modern browsers support all of these versions. Of course we are
aiming to stay current and complete our websites in either HTML5 or HTML 4.01.

WHATWG
WHATWG stands for The Web Hypertext Application Technology Working Group. Say that
5 times fast! The purpose of this group is to standardize modern web frameworks like
HTML5. The history of this is that the W3C was working on XHTML 2.0 as a means of
making HTML a more strict markup language to work with application based websites.
XHTML was not popular with the web community, and HTML5 has become the go to
technology for modern web applications. HTML5 is really a bit of a loose term in that it
refers to a collection of technologies encompassing markup, design, and behavior. Think
HTML, CSS, and JavaScript to be more precise. At this stage of the game, we have the
WHATWG and W3C versions of HTML5 and they do not one hundred percent agree on
what the actual meaning of HTML 5 is. What they do agree on however, is the markup
portion of HTML5.

HTML5 Document Structure


A complete HTML Document has many important parts. We’re going to look at some
example HTML but before we do, we need to consider what type of application you will use
to edit your HTML. There are several great free options available. I like Adobe Brackets,
however you are free to use whatever you like. It is also possible to simply use a super
basic text editor like Notepad but you’ll miss out on some nice auto format features that
really help to make the markup much more readable. Here is a basic HTML5 document
structure.
<!doctype html>
<!-- HTML5 Document Structure -->

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
Example HTML Document
</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>

<body>

<h1>
This is some text inside of an H1 tag which is good for section titles.
</h1>
<p>
This text is part of a paragraph. This is good for many sentences grouped together by related
ideas.
</p>

</body>

</html>

This is about as simple as it gets, but it allows us to look at some of the key ideas with
regard to the markup in use. Let’s review them now.

• Doctype The doctype declaration is to tell the browser what version of HTML to
expect to parse within the document. I love this new doctype declaration in HTML5
because it is so simple unlike the clunky, attribute filled doctypes of the older
versions of HTML. <!doctype html> informs the browser that we are dealing with a
Standards Based Document.
• Comments We can see a comment included by the code <!– HTML5 Document
Structure –> Comments help developers to keep track of large complicated themes
that may be compiled out of many different files.
• Dom Tree Starting at <html lang=’en’> and ending with </html> is the Document
Object Model Tree. At the root of tree is the html tag itself. This is an example of a
container in HTML since it has both an opening and closing tag. Note that only
opening tags will have attributes, closing tags will never have attributes.
• Parent Child Relationships The concept of a container brings up the idea of Parent
and Children elements. Tags that are contained within another are children of their
parent. In this document the meta, title, and link tags are children of the head
element.
• Sibling Relationships When we think of Siblings, we think of equals. For example,
you and your brother or sister are siblings, and equal so to speak in the family tree.
In this HTML document, the head and body tags could be considered Siblings.
Tags and Containers
Tags are the basis of HTML and there are a few ways to write and interpret them.
Specifically, there are tags that create containers and those that do not. First up we’ll look
at the idea of a container tag. In our example HTML above, we have a title tag with both an
opening <title> and closing </title>. Between the tags is some text. The entire structure is
referred to as an element on that page, and since the opening and closing tags surround
the text it is also considered a container.
Meta tags on the other hand are en example of a non containing tag. A opening meta does
not need the equivalent closing meta. This is referred to as a standalone tag. Often times
you will see the format of auto ending the tag via a forward slash like so <meta
charset="UTF-8" /> This example has an attribute of charset and a value of UTF-8.
It may seem a bit mundane, but tags really are the basis of all that we do in web
development. It pays to understand them at a low level, in order to make higher level
problems easier to debug and troubleshoot later on.

Content Models in HTML5


In prior versions of HTML there were two main content models or categories of elements.
There were block elements that defined areas of a document, and inline elements that
would flow with text. HTML5 takes this concept a step further and supports Seven different
types of Content Models. Content models are what define what types of content are
expected in certain types of contexts. A given element should only have content that
matches the requirements of it’s Content Model. The seven content models overlap,
meaning some elements may belong to more than just one content model.
1. Flow
Most elements in the body of the webpage will be of the Content Model Type Flow. This
would include text, paragraphs, headings, lists, hyperlinks, images, audio, video, and most
other things things in HTML. Flow pretty much encompasses everything except metadata.
2. Phrasing
The phrasing content model includes the text of the document and any elements that
markup that text. This would include thinks like images, links, forms, bold, and italics.
3. Heading
The heading content model refers to all of the heading elements like h1 h2 h3 h4 h5and h6.
4. Sectioning
The sectioning content model refers to the new section elements in HTML5. You may have
seen these out on the web in the forms of article aside nav and section.
5. Embedded
The embedded content model is responsible for importing another resource into the
document like audio or video. Images, Canvas, Math objects, and so on would be
considered part of the embedded content model.
6. Interactive
Interactive content model elements are specifically meant for users to take action on. A
menu navigation, form input, or hyperlink would all be part of the interactive content model
group where user input is required.
7. Metadata
Content that sets up the presentation or behavior of the rest of the document. This is
basically information about information. Meta data is very useful not only for your own
webpage, but also if you are integrating other services from third party plugins or websites.
For example, Facebook provides a large collection of meta tags to insert on your webpage
to integrate with various aspects of it’s developer api.
These seven content categories are a great overview of the type of data you will be
working with in HTML5. Having a firm grasp of their meaning and use will enable you to
write conforming documents that are portable and maintainable across a range of devices
for the foreseeable future.

Obsolete HTML5 Elements


In HTML5, many html elements have been declared obsolete. The meaning of this may be
a touch misleading. Since the internet is so incredibly big, there are many pages out there
that still use many or all of the elements deemed obsolete. These pages will still work, but
being obsolete, their creators should no longer use these elements when they build new
online websites. It is a best practice to cease using any of the following elements moving
forward.

• acronym
• bgsound
• dir
• frame
• frameset
• noframes
• isindex
• listing
• nextid
• noembed
• plaintext
• rb
• strike
• xmp
• basefont
• big
• blink
• center
• font
• marquee
• multicol
• nobr
• spacer
• tt

You may be wondering, why would they remove functionality from the language? Wouldn’t
I want to be able to accomplish just as much, and more with this great new HTML5? Well,
in reality, you can accomplish all the things these obsolete tags provide by using a
combination of supported HTML5 elements and additional CSS and or JavaScript. If you’re
trying to use the blink tag these days, you need to reevaluate your approach!
In addition to the obsolete elements, there is a large collection of obsolete attributes as
well. Let’s review them here

• abbr
• accept
• align
• alink
• archive
• axis
• background
• bgcolor
• border
• cellpadding
• cellspacing
• char
• charoff
• charset
• classid
• clear
• code
• codebase
• codetype
• color
• compact
• coords
• datafld
• dataformats
• datapagesize
• datasrc
• declare
• elements
• event
• for
• frame
• frameborder
• height
• hspace
• language
• link
• longdesc
• lowsrc
• marginbottom
• marginheight
• marginleft
• marginright
• margintop
• marginwidth
• methods
• name
• nohref
• noshade
• nowrap
• profile
• rev
• rules
• scheme
• scope
• scrolling
• shape
• size
• standby
• summary
• target
• text
• type
• urn
• usemap
• valign
• valuetype
• version
• vlink
• vspace
• width

Again, this just means that there are better ways to accomplish the same things. If you’ve
been developing web pages for a good period of time, you may be laughing as you look at
this collection of elements and attributes that have been deemed obsolete. Some of the
early WYSIWYG or What You See Is What You Get tools made abundant use of almost all
of these elements and attributes As they say, hindsight is 20 / 20.

Conclusion
I chose to really dig into HTML and HTML5 in this new series here at VegiBit because
there does seem to be a fair amount of confusion as to what HTML5 actually is. And you
know what, for good reason. The collection of standards and standards bodies governing
the future of the web, not to mention the influence billion dollar corporations have on how
things are being shaped, is enough to drive anyone mad. I once heard a saying about
HTML5: “Everyone is using it, nobody knows what it is!” Quite fitting in fact. This first jump
into the basics of HTML5 will get us going in the right direction to have a better
understanding of the tools we use everyday.

Digging In To HTML Fundamentals

HTML has many fundamentals to be aware of. Whether we’re dealing with
HTML comments, HTML whitespace, Block Level elements, or inline elements,
there are several building blocks to memorize. Knowing these important key
concepts will pave the way for our HTML5 learning. Let’s jump right in!

Whitespace and Comments


Whitespace is a term that describes characters which do not usually display anything when
rendered on a page. Tabs, spaces, breaks, and so on are all whitespace characters.
HTML basically ignores whitespace. More accurately, it compresses many whitespace
characters down into one. To see an example of how this works, let’s look at some code.
First, we will show the code with a collection of really random whitespace characters. Next
up, we will Beautify the source code. Beautification simply means to use an IDE Integrated
Development Editor to apply very pleasing to the eye spacing and formatting to the source
code to increase readability. Then we can compare the result in the browser.
<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8" />
<title>
Fresh Style
</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>

<body>

<h1>
Style Example
</h1>

<p>
This is a paragraph with some fresh style. It needs more than one sentence, so this is the second
sentence.
</p>

<p>
You can have more than one paragraph on a page. If you didn't know that, now you know.
</p>

<p>
One is the lonliest number, two is company, and three is a crowd. Guess which one this paragraph
is.
</p>

</body>

</html>

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8" />
<title>
Fresh Style
</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body>
<h1>
Style Example
</h1>
<p>
This is a paragraph with some fresh style. It needs more than one sentence, so this is the second
sentence.
</p>
<p>
You can have more than one paragraph on a page. If you didn't know that, now you know.
</p>
<p>
One is the lonliest number, two is company, and three is a crowd. Guess which one this paragraph
is.
</p>
</body>

</html>

Both examples of HTML are telling the browser to do the same thing. It may not look like
that based on what the source looks like, but if we view this in the browser, we can see
both options give the same result.

You can be as sloppy as you want to! The browser will still recognize your chicken scratch
of HTML markup! Of course we don’t actually want to do this. As your webpages grow and
become more complicated, the nice formatting is going to pay big dividends to keeping
your sanity in check. Definitely try to keep your source code as neat and tidy as possible.
Comments are also whitespace when they are rendered in the browser. So if you add
several lines of comments to help with the meaning of your HTML source, it will be treated
as one space as the browser engine collapses multiple whitespace characters into one.
Using Paragraphs to Display Text
As you write several lines and sentences of content in your webpage, you will need a way
to organize the text into easy to read chunks. The best way to do this is to simply make
use of the paragraph or p elements on your page. In the example above, it was easy to
group together three different groups of text into three different paragraphs. Even though
you can easily place the text outside of the p tag, it is better to contain it within the
paragraph as it is much easier to style and format. To recap, paragraphs are created with
the p element, and then styled using css.

Applying Style to HTML Elements


In the bad old days of web design, whoops, I mean good old days of web design, we were
subject to styling elements with by using some of the built in styling mechanisms of HTML
itself. These days, there is no styling built into the markup, it is all done via CSS or
Cascading Style Sheets. We were able to assign some style to the example snippet of
HTML by way of an external stylesheet. We placed the following CSS code in the main.css
file
html, body, div, span, h1, h2, h3, h4, h5, h6, p, ol, ul, li,
blockquote, pre, form, label, legend, table, caption, tbody, tfoot, thead,
tr, th, td, article, aside, canvas, details, embed, figure, figcaption,
footer, header, hgroup, menu, nav, output, section, summary, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}

body, p {
line-height: 1;
font-family: Georgia, serif;
font-size: 16pt;
}

p, h1, h2, h3, h4, h5, h6, ol, ul, li { margin: 12pt; }
li { margin-left: 2em; }

h1, h2, h3, h4, h5, h6 {


line-height: 1;
font-family: Tahoma, Verdana, sans-serif;
font-weight: bold;
}

h1 { font-size: 200%; }
h2 { font-size: 180%; }
h3 { font-size: 160%; }
h4 { font-size: 140%; }
h5 { font-size: 120%; }
h6 { font-size: 100%; }

pre { font-family: consolas, monospace; }

We could also have placed this CSS inline, meaning in the same HTML page. Don’t do
this! You pretty much always want to put your CSS code into it’s own file and link to it via
the link tag. The link tag is a standalone tag, not a container, which has three attributes
that should be set. The first attribute is rel with a value of stylesheet, the second
is type with a value of text/css, and the third is the href with a value of main.css. The href
is a document relative file path, so if your CSS is in a different folder, simply include the
path to the folder in this attribute value. The CSS file may even be located somewhere in
the cloud via a CDN Content Delivery Network and if that is the case, just provide that file
path as well, it will still work.
Styling is going to come in very handy. If the CSS is removed from our example HTML, it is
quite bland indeed.

Block vs Inline Elements


Many times you may have been designing a web page and the layout of elements on the
page seem to have a mind of their own. Often times, this is caused by the differences of
block level vs inline level elements. Inline means that the element or object in question is
part of the overall flow. Block level takes it’s own space and occupies the entire width of
the page using the height of itself. Another way of saying this is that block level elements
take up vertical space. Inline follows the left to right flow, wrapping when needed.
<address> <article> <aside> <audio> <blockquote> <canvas>
Block level elements include
<dd> <div> <dl> <fieldset> <figcaption> <figure> <footer> <form> <h1> <h2> <h3>
<h4> <h5> <h6> <header> <hgroup> <hr>
<b> <big> <i> <small> <tt> <abbr> <acronym> <cite> <code>
Inline level elements include
<dfn> <em> <kbd> <strong> <samp> <var> <a> <bdo> <br> <img> <map> <object>
<q> <script> <span> <sub> <sup> <button> <input> <label> <select> <textarea>

The Purpose of the Head Tag


When reading a book, we’ll often take a moment to look at the front cover, the matter of
the book, and table of contents. This gives us a good outline of what we are about to
embark on, as well as a helpful outline. This is some information, about the information in
the book. It works the same way in HTML. The head tag contains all of the meta data that
will be useful for web browsers and search engines to properly interpret your page. Many
useful elements go in the head area of the page. Here is a table of the elements you will
use.
Tag Description

<head> Defines information about the document

<title> Defines the title of a document

<base> Defines a default address or a default target for all links on a page

<link> Defines the relationship between a document and an external resource

<meta> Defines metadata about an HTML document

<script> Defines a client-side script

<style> Defines style information for a document

Using CSS to Apply Style


We already saw how to apply style to HTML in a page by using the link tag to link to an
external style sheet. The Cascading nature of CSS is what gives us the ability to override
styles in the external style sheet by placing the style right into the HTML file. Making a
habit of this might not be the best idea since it will cause things to become muddied over a
period of time. In order to avoid cruft, it’s better to keep those styles right where they
belong, in your external style sheet. There are times when you will need the ability to place
the style right in the head of the HTML document, or even inline right to the element itself.
The order of precedence goes as follows. Inline has the highest, Style in the head element
comes next, and external style sheets are given least precedence.
<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8" />
<title>
Fresh Style
</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<style>
p {
background-color: #E3E3E3;
}
</style>
</head>

<body>
<h1>
Style Example
</h1>
<p>
This is a paragraph with some fresh style. It needs more than one sentence, so this is the second
sentence.
</p>
<p>
You can have more than one paragraph on a page. If you didn't know that, now you know.
</p>
<p style="background-color:#D6E9C6">
One is the lonliest number, two is company, and three is a crowd. Guess which one this paragraph
is.
</p>
</body>

</html>

By applying a specific style to an element in the HTML page using the style tag in
the head tag of the document, you can see that the three paragraphs now have a
background color. For the third paragraph we applied a style inline on the element itself, so
in that case, it overrides anything in both the external style sheet and the style in the head
of the document. Awesome Stuff!

Add JavaScript to HTML


There are several ways to include JavaScript in your HTML page. Just like CSS, you can
place the JavaScript inline, but it’s much better to place the JavaScript in an external file.
VegiBit has a great series how to learn JavaScript and you are welcome to check out
those tutorials to get up to speed on all of the JavaScript Fundamentals you’ll need to
know. For brevity and completes, we’ll include a simple example here.
<!DOCTYPE html>

<html>

<head>
<title>
Including Javascript in HTML
</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<script>
function count() {
var n = 0;
e = document.getElementById("counter");
setInterval(function () {
e.innerHTML = ++n;
}, 1000);
}
window.onload = count;
</script>
</head>

<body>

<h2>
Including Javascript in HTML
</h2>

<h3>
Watch this counter increment! <span id="counter">0</span>
</h3>

</body>

</html>

Your little JavaScript application is happily ticking along, displaying a number value to the
screen once every second. Another great resource for learning about HTML and
JavaScript together is the JavaScript Events Tutorial, do check it out!
The HTML Meta Tag
Metadata is data about data. Say Whay?! Sounds funny right? Well, it is actually very
useful. The meta tag give overview information about the current HTML page. The
metadata is not actually displayed on the visible page, but rather to give useful information
to the browser and search engines.
The common uses of meta elements are to specify keywords, page description, last
modified information, author of the page, and others.
Providing keywords for search engines
<meta name=”keywords” content=”HTML, CSS, PHP, HTML5, JavaScript”>
Give a description to the web page
<meta name=”description” content=”Free Web tutorials on PHP, JavaScript, HTML
and CSS”>
Define the author of the webpage
<meta name=”author” content=”Vegi Bit”>
Refresh the page every 25 seconds
<meta http-equiv=”refresh” content=”25″>

Search Engine Optimization


SEO is a bit of a misnomer. There used to be a class of webmasters that would try to push
their websites higher in the search engines using all kinds of tricks. This is largely
ineffective. What really matters is the content in the page, as well as the structure of the
HTML document and overall website. Think of SEO as being a neat freak. Do you like to
have everything lined up just right, tools placed in their proper locations, dishes put away
in the right cabinets, food in the right location in the refrigerator and so on? Then you my
friend are going to be great at Search Engine Optimization. You see the search engines do
not need to be optimized for at all. They are simply trying to provide the best answer or
result to the search question or query typed in by the user. If your content provides a
workable solution to the search users problem, and your HTML is clean and well
structured, then you may get a visit from the search engine based on this. In short, just
create the best content you can, along with the most semantically proper HTML that you
can, and your webpage will be found just fine in the search engines and your traffic should
benefit from it.

The Top 11 Most Important HTML Text


Features to Learn
We’re moving onward and upward in getting HTML and HTML5 solidly into the
grey matter between your ears! In this magnanimous HTML tutorial, we’ll be
covering many features relating to text to give your online content that special
sauce. Some folks go for the every Peppery Sriracha sauce, whilst myself, I
think I’ll go with Franks Red Hot. Have you tried that stuff on Bacon? It’s
awesome! Now that your taste buds are primed, let’s keep going with Text in
HTML!

Working With HTML Line Breaks


The browser will usually be the determining factor on where to wrap lines of text in your
page based on the size of the device looking at the content, the CSS in use, the size of
characters, and so on. If you would rather have more control over how this happens, you
can insert your own line break by making use of the trusty <br> tag. You surely have made
use of this technique when trying to format your text.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
HTML Text and Line Breaks
</title>
</head>

<body>

<h1>
HTML Text and Line Breaks
</h1>
<p>
This here is a lot of text. It is really random, but if you surely can't handle seeing another
bunch of lorem ipsum in to world. So in the sprit of our hot sauce, and Franks Red Hot and Bacon,
let's consider how tasty it really is. If you haven't had the Franks Red Hot, you will. By the powers
vested within something, it is so.
</p>

<p>
Effictive immediately, the campaign for the elimination of lorem ipsum has officially begun. If you
are caught using a lorem ipsum in your HTML demo, there will be repercussions. Repercussions of the
like, including, but not limited to, well... Some crazy stuff. Now eat that bacon.
</p>

</body>

</html>

In this small snippet of HTML here, we will view how the browser handles the flowing
poetry and observe where lines wrap. Once complete, we can insert a <br> tag after every
single period in the prose to see what happens. Observe Grasshopper.

Get Your Phrase On


Phrase elements are able to markup text in the document based on their use case. By
doing this, the browser and search engines have a better understanding of the semantic
meaning of the elements, which otherwise may not be apparent in the display on the
webpage. You are familiar with these of course by playing witness to the large use of bold,
emphasis, and other phrase tags. Here is a snippet of some frequently used Phrase
Elements in HTML.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
Get Your Phrase On
</title>
</head>

<body>

<h1>
Get Your Phrase On
</h1>

<div style="margin: 50px">

<p> <em> Emphasize </em>


</p>
<p> <strong> Strong </strong>
</p>
<p> <dfn> Define a term </dfn>
</p>
<p> <code> Code listings
</p>
<p> <samp> Sample </samp>
</p>
<p> <kbd> Keyboard </kbd>
</p>
<p> <var> Variables </var>
</p>

</div>

</body>

</html>
Yes, Yes it is my friend. As you can see here, this is bare bones display.
Hey that’s cool!
There’s nothing quite like the beauty of a piece of HTML being rendered in the browser
with absolutely no styling whatsoever. By using the phrase elements on HTML, we can
give meaning to elements, separate from the display of said elements. Now you can of
course style any of these elements to your hearts content, much the way the
awesome Twitter Bootstrap Framework does, but in this case we’re simply having a
friendly review of what’s available in bare bones HTML.

Controlling The Font


HTML gives you the ability to control many things about the font of the text on the page,
even without any CSS. Why would you want to do this? I’m not sure actually, CSS is the
far more powerful way to do something like this, but HTML does provide this ability, so
we’ll take a look at it. Actually, I can think of a really interesting friggin awesome one, and
that is the <s> Strikeout </s> tag. Let’s look at all the other options available to us as well
now.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
Controlling The Font
</title>
</head>

<body>
<h1>
Controlling The Font
</h1>

<div style="margin: 50px">

<p> <b> Bold </b>


</p>
<p> <i> Italic </i>
</p>
<p> <u> Underline </u>
</p>
<p>This is a <sub> subscript </sub>
</p>
<p>This is a <sup> superscript </sup>
</p>
<p>This is <small> small </small>
</p>
<p> <s> Strikeout </s>
</p>
<p> <del> Delete </del>
</p>

</div>

</body>

</html>
So there you go, you can see we have several interesting and meaningful ways to markup
the font on the webpage when needed.

Use Mark to Highlight Text


You may have seen this technique used on all those crappy one page sales pages on the
internet. You know the ones that give you ten million reasons why you need their widget /
info product / useless item, and every other line of text is highlighted with a yellow
background. Well friend, you will now have the ability to be just as annoying by making
liberal use of the <mark></mark> html tag. We’ll just add it to some existing HTML from
earlier and check out what happens.

Using Headings In Your Webpage!


Headings are a fantastic way to add style to your content, as well as telling the search
engines what is important on your webpage. The various headings assign different sizes
based on which one of the six available heading options you use. Heading is a block level
element and can include other block level elements if needed. Check out the six options
here.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
Using Headings In Your Webpage!
</title>
</head>

<body>
<h1>
Using Headings In Your Webpage!
</h1>

<div style="margin: 50px">

<h1> Heading 1 </h1>


<h2> Heading 2 </h2>
<h3> Heading 3 </h3>
<h4> Heading 4 </h4>
<h5> Heading 5 </h5>
<h6> Heading 6 </h6>

</div>

</body>

</html>

By using the different headings correctly, you’ll be sure that the webpage follows a useful
outline or hierarchy. Again, this structure helps both the reader and the search engines to
properly digest your content to its max.

Quote Marks and Quotations in HTML


Quotes and quotation marks are common in the web publishing industry. It is easy to add
these right into the HTML using the <q> element in your page. The benefit is that it adds
additional meaning to the quote beyond just the presentation on the page, much like the
many Phrase elements we looked at earlier.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
Quote Marks and Quotations in HTML
</title>

</head>

<body>

<h1>
Quote Marks and Quotations in HTML
</h1>
<p>
Bacon has been found to be a beneficial addition to the diet of all people <q>in the whole
world.</q> This is in now way an endorsement for you to eat more bacon.
</p>

<blockquote>
Eat Bacon on an as needed Happiness Basis!
</blockquote>

</body>

</html>

Preformatted Text Rocks


If you program in PHP, you likely are familiar with the handy <pre> tag. By using
the <pre> tag in testing, array output and object output to the browser become much more
readable. In this case, we’re just taking a look at using the <pre> tag in some HTML. What
it does is essentially turn off the automatic whitespace compression that takes place in the
browser when rendering HTML. This way you can create some text in the editor that will
display based on exactly how you configured the outline using the whitespace included.
You’ll see this oftentimes when people use text characters to create cool artwork.
You’ll notice that the code above has no <pre> tag in it. The first screenshot shows that
the browser clobbers our text formatting but if we add the <pre> tag to the HTML, it does
output nicely.
<!DOCTYPE html>

<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
Preformatted Text Rocks
</title>
</head>
<body>

Imagine That You


Wanted To Display
Some Text In
A Very Specific

Way

This is easy to do the the pre tag!

This is a bird in a tree using nothing but text!

('>
/))@@@@@.
/@"@@@@@()@
.@@()@@()@@@@
@@@O@@@@()@@@
@()@@@@@()@@
@()@||@@@@@'
'@@||@@@'
||
||
||
||
^^^^^^^^^^^^^^^^^^^^^^^

</body>
</html>
List Types in HTML
HTML provides nice ways to present content in lists. In this example we’ll take a look at
Ordered Lists, Unordered Lists, as well as the under used Definition List.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
List Types in HTML
</title>
</head>

<body>

<h1>
List Types in HTML
</h1>

<ol>
<li>This is the first li</li>
<li>This is the second li</li>
<li>This is the third li</li>
</ol>

<ul>
<li>I'm unordered!</li>
<li>So am I!</li>
<li>You guessed it!</li>
</ul>

<dl>
<dt>HTML</dt>
<dd>A Markup Language for presenting content on the world wide web.</dd>

<dt>PHP</dt>
<dd>A Fantastic scripting language that provides dynamic websites and runs on the server.</dd>

<dt>CSS</dt>
<dd>Used to apply style to HTML elements.</dd>

<dt>JavaScript</dt>
<dd><s>The religion of Douglas Crockford</s> Used to add interactivity and behavior to static web
pages.</dd>
</dl>

</body>

</html>

We can look at how these elements display in the browser here. Again, this is bare bones
HTML, so the presentation is a bit bland. Out in the wild, most web designers will use CSS
to make list elements look super slick. Often times, the list elements are simply used as
organizational elements, and the CSS applied to them hides their actual list like nature.
Controlling Text Direction in HTML
Though there probably isn’t a huge need for controlling the text direction when using
English in your website, it can be useful for other languages such as Hebrew. In this case,
text is actually written left to right. Confusing if you ask me! By setting the bdo tag, or
bidirectional override, the text will then appear reversed in the page. Let’s check out the
results when applying this to some existing HTML.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
Controlling Text Direction in HTML
</title>
</head>

<body>

<h1>
Controlling Text Direction in HTML
</h1>
<p>
<bdo dir="rtl">This here is a lot of text. It is really random, but if you surely can't handle
seeing another bunch of lorem ipsum in to world. So in the sprit of our hot sauce, and Franks Red Hot
and Bacon, let's consider how tasty it really is. If you haven't had the Franks Red Hot, you will. By
the powers vested within something, it is so.</bdo>
</p>

<p dir="rtl">
Effective immediately, the campaign for the elimination of lorem ipsum has officially begun. If you
are caught using a lorem ipsum in your HTML demo, there will be repercussions. Repercussions of the
like, including, but not limited to, well... Some crazy stuff. Now eat that bacon.
</p>

</body>

</html>
Word Break Suggestion
There may be times when you would like to control how a long string of text wraps in the
page. You can do this with soft hypens or the <wbr> tag. The difference is that the soft
hypen &shy; will break the string and add a hyphen at the break point. The <wbr> tag
breaks the word at the specified point, without adding a hypen. You can test this in your
HTML and see the result.

Ruby Characters
Ruby is a super popular programming language with widespread acceptance due to the
Ruby on Rails framework. This Ruby however, is not referring to the programming
language. In this instance, Ruby Characters are referring to annotations which show
pronunciation. HTML has a <ruby> tag to allow you to make use of these annotations in
your web page.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
Ruby Characters
</title>
</head>

<body style="margin: 100px;">

<h1>
Ruby Characters
</h1>

<p>
The two ideograph symbols in this Japanese text has a hiragana annotation.
</p>
<p lang="ja" style="margin: 100px; font-size: 200%">
<ruby>

<rp>(</rp>
<rt>かん</rt>
<rp>)</rp>

<rp>(</rp>
<rt>じ</rt>
<rp>)</rp>
</ruby>
</p>

<p>
This instance is written in simplified Chinese and the pinyin is the annotation here.
</p>

<p lang="zh-CN" style="margin: 100px; font-size: 200%">


<ruby>

<rp>(</rp>
<rt>hàn</rt>
<rp>)</rp>

<rp>(</rp>
<rt>zì</rt>
<rp>)</rp>
</ruby>
</p>

</body>

</html>
Working With HTML Images

The HTML image tag is an inline element however there will be instances when
flowing text around an image is desired. In fact, this happens all the time. If
you’ve worked with images in HTML, you’ll know that at times it seems like the
image has a mind of its own in regard to where and how it gets displayed on the
page in relation to text. Let’s take a closer look at embedding images in our
webpages, and how to format them so that images and text can live in
harmony. In fact, in looking at the opening text of this tutorial, we are using one
of the very techniques we will discuss. Let’s begin!
First we’ll need to whip up some HTML with an image so that we can complete some tests.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>Working With HTML Images</title>
</head>

<body>
<h1> Working With HTML Images </h1>

<img src="images/html.png" width="240" height="240" alt="html 5 logo" title="html 5 is the language


of the web." />

<p>Web Developers use HTML to build websites for the Internet. The Internet is also known as the
World Wide Web. HTML is not the only technology in use however. You may also run across CSS,
JavaScript, Ruby, PHP, and SQL. All of these pieces of the puzzle fit together to create something of
value. It is fun to read text, yes it is.</p>

<p>You may like chicken. Your friend may prefer only fresh fruits and vegetables. Leafy Greens are
likely the best bet for you. The other day, I had a delicious lunch at an Italian restaraunt. Have
you had yourself a nice bowl of Pasta lately with some nice red sauce? I'm sure you have, but if you
have not, it is important that you do.</p>

<p>If it comes to your attention, you'll notice this is nothing more than gibberish. Due to the war
on lorem ipsum, nonsense text has become the defacto standard for working with agile mockup tutorial
text snippets. Focusing on the low hanging fruit will yield dividends in the same space of time. Yes
if you must, you can do just that. Have a great day!</p>

</body>

</html>

As you can see, there is nothing special about this snippet of HTML. Of course if you read
the sample text, you may be enlightened by a few of the words of wisdom provided, but
beyond that – this is pretty simple stuff. This is a basic HTML Web Page which supports
HTML5 based on the doctype, it has some basic head information, an h1, an image, and a
few paragraphs. We can view it in the browser and it displays as you see here.

The image is all by itself, but not because it is block level. The paragraph begins after the
image tag, so the text starts at that point. How about if we’d like to have the text flow
around the image instead. We can do this with CSS. For brevity, we’ll just put the style
rules right in the head of the document. The following code will now be inserted.
<style>
img {
float:left;
}
</style>
That looks a little better. By applying the css float property to the image tag, we
There we go!
can control how text flows around an image. It looks ok, but it feels a little cramped. The
text is smacked right up against the image. Let’s give the layout a little breathing room. By
adding some margin values to the CSS like so
<style>
img {
float:left;
margin-right: 50px;
margin-bottom: 10px;
}
</style>
We’ll notice that the text now has plenty of space between itself and the HTML5 logo. This
looks a little better.

Just as we can float an image left, floating the image right is just as easy. We’ll float left,
and also change the margin-right to margin-left so that it looks uniform. With the new code
of
<style>
img {
float:right;
margin-left: 50px;
margin-bottom: 10px;
}
</style>
The page will now look like this.

That looks pretty good. Understanding how to float text around your images is going to
reduce your frustration levels twenty fold, trust me!
One thing to note about assigning the float property to images is that it converts the
element from inline to block level. This will have an impact on other CSS design that may
be applied to the element.

Dealing With Multiple Images


Ok so we’re happy, we know how to align text with images and all is right with the world.
Let’s add another image to the page so we can see how things work. We’ll add the next
image using this snippet of HTML:
<img src="images/html.png" width="240" height="240" alt="html 5 logo" title="html 5 is the language
of the web." />
<img src="images/javascript.png" width="240" height="240" alt="javascript logo" title="Douglas
Crockford wrote JS Lint" />

Now, you would think that these two elements would stack on top of each other by looking
at the source code. What happens in the web page when we load it in the browser is a little
different though. This is the result so far.
you say. Maybe you didn’t quite expect the images to display side by
Hey that looks really good!
side, but hey, you’re of the easy going variety and it looks acceptable so good enough,
right? Well, it’s all good except for one problem. Your picky client keeps talking about their
competitor and how great their stacked images look on their marketing page. He feels so
attached to this stacking look, that he has decided that you don’t get paid until images
stack. What’s a friendly Web Developer to do? Well, in this case, the clear property may be
just what the doctor ordered. Let’s add it to our CSS markup like so.
<style>
img {
float:right;
clear: right;
margin-left: 50px;
margin-bottom: 10px;
}
</style>
Boo Yeah!! One word: Stacked. Good work Grasshopper.

HTML Floats – Break it Down


As text flows around an image, you may run into a scenario where you would like to break
a portion of the text so it begins after the image. This is possible using the clear property,
let’s see how to do it. Here is some new HTML to work with here.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
HTML Floats - Break it Down
</title>
<style>
img.float-right {
float: right;
margin-left: 12px;
margin-bottom: 7px;
border: solid blue 1px;
padding: 3px;
}
.clear {
clear: both;
}
</style>
</head>

<body>

<h1>
HTML Images
</h1>

<img src="images/css.png" width="240" height="240" alt="CSS" TITLE="CSS controls your presentation"


class="float-right" />
<p>
There was a time when you thought you were free of nonsense text. This was not true however, as you
are witnessing all kinds of text on the screen now and it's likeness is of the nonsense variety. And
speaking of that, have you had any good mexican food lately? A delicious burrito could do me good
right about now. Let's see, how about some nice Chicken, Salsa, Refried Beans, Sour Cream, Triple
Cheese Blend, and Guac. That should do it.</p>
<p>
At this time, we have entered the second paragraph. It is text and it is in a paragraph. Now that
we have have had some yummy dinner, we can move on to desert. What shall it be? I'm partial to
chocolate so lets look at the double fudge, mud pie, special with vanilla ice cream and whip cream on
top. Normally, this much food is not consumed, however we need a lot of nonsense text, so we need to
keep eating.</p>
<p>
The last paragraph of text is now in play. We can ponder the benefits and drawbacks of using
prebuilt frameworks in the various applications you may build. Maybe you're writing in Ruby, so Rails
is likely your framework. If you plan to use JavaScript, you will have way too many choices. Likewise
with PHP. There are more frameworks than you can shake your booty at. Speaking of shaking booties, do
you like to play Just Dance. It may be of benefit to play Just Dance, as it will generate dance moves
as you feel the grooves.</p>

</body>

</html>
Cool! This looks pretty good. Now let’s consider the second paragraph where we have
finished dinner, and moved on to dessert. Perhaps we’d like that second paragraph to
begin after the image. Let’s see how to do that. We’ll make use again of the CSS property
clear which is used to clear floating objects like an image. You can specify a value for clear
of right, left, or both. In this example, by adding this css
#hack {
clear: right;
}

and this markup to the paragraph in question


<p id="hack">
At this time, we have entered the second paragraph. It is text and it is in a paragraph. Now that
we have have had some yummy dinner, we can move on to desert. What shall it be? I'm partial to
chocolate so lets look at the double fudge, mud pie, special with vanilla ice cream and whip cream on
top. Normally, this much food is not consumed, however we need a lot of nonsense text, so we need to
keep eating.</p>
<p>
We get the exact result we were looking for!

Have a play around with the other clear options to see how they work in your web pages.
You’ll love the control the clear property is able to provide when dealing with floating
elements on the page.

Image Maps in HTML


In HTML you can define regions of one image that all point to different links that you
specify. This is what is known as an image map, and they are really cool. In looking at the
HTML below, you’ll notice that the image we are using has a new attribute called usemap.
The attribute has a value of #imagemap. This is the name of the map. This tells the image to
look for a <map> tag which has the name of #imagemap. Inside of the <map> tag are
several <area> tags, each one defining a hotspot on the image that will now contain a
hyperlink to another URL. In the example here, we only used the rectangle and circle
options however you could also make use of the polygon shape if you like. The image
render after the HTML markup is a live example, go ahead and click the different areas on
the image and see where they take you!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Image Maps in HTML</title>
</head>

<body>
<img src="images/imagemaps.jpg" width="400" height="300" usemap="#imagemap">
<map name="imagemap">
<area shape="rect" coords="6,39,126,137" href="http://vegibit.com/what-is-html/" alt="what is
html">
<area shape="rect" coords="136,40,249,140" href="http://vegibit.com/digging-in-to-html-
fundamentals/" alt="html fundamentals">
<area shape="circle" coords="316,96,55" href="http://vegibit.com/the-top-11-most-important-html-
text-features-to-review/" alt="html text features">
<area shape="rect" coords="383,46,485,145" href="http://vegibit.com/getting-started-with-
javascript-programming/" alt="get started with javascript">
<area shape="rect" coords="17,174,126,273" href="http://vegibit.com/javascript-code-structure/"
alt="javascript code structure">
<area shape="rect" coords="141,172,245,274" href="http://vegibit.com/javascript-functions-
tutorial/" alt="javascript functions">
<area shape="circle" coords="320,215,59" href="http://vegibit.com/javascript-events-tutorial/"
alt="javascript events">
<area shape="rect" coords="384,165,486,276" href="http://vegibit.com/document-object-model-
tutorial/" alt="document object tutorial">
</map>
</body>

</html>

HTML Hyperlinks Tutorial


Hyperlinks are what make the internet an actual internet. Without our trusty
hyperlinks, there wouldn’t be much inter in the net now would there? Hyperlinks
are pretty simple in many ways, we click hundreds of them every day. When
you start to dig into their structure a little more closely however, you’ll uncover
useful and powerful attributes about them that will help you to be a better web
developer. In this episode, we’ll take a close look at things like Uniform
Resource Locators, Relative URLs, Base URLs, Image Links, and more. Let’s
jump right in and get started building some links.

Uniform Resource Locator


The short hand of the Uniform Resource Locator is quite simply URL. Surely you are
familiar with them, as you needed to visit one in order to read this webpage! The technical
definition for an URL is a way of specifying the location of a given resource on the web.
Now often when we think of URL’s we simply think of it representing a website address we
can type into the browser window. While this is true, the URL can specify any number of
different types of resources including webpages, images, files, or even an API. We can
break down a URL like so:
http://www.vegibit.com:80/thing?variable1=value1&variable2=value2#location
The components of this Uniform Resource Locator break down like so.
scheme http:// The scheme tells us the protocol in use. In web development this is
usually http:// or https://
host www.vegibit.com The host name is the domain or ip address that has the
resources you are looking for.
port :80 The port field tells us what TCP port is in use for this URL. This can usually
be omitted.
path /thing The path contains the path to the resource you want access to.
query string ?variable1=value1&variable2=value2 The query string is used to pass
name value pairs to the server.
fragment identifier #location This field can be used to jump to a specific location in
a given web page.

Creating HTML Hyperlinks


It’s a good thing to know all the parts of an URL like we investigated above. We surf
around the internet with easy, often times not even really knowing what each piece of the
address we use means. We have been reduced to pointers and clickers. Point the mouse,
click away! The Hyperlink is the tool we need to create those links for our users. It’s easy
to do, let’s see how.
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
Creating HTML Hyperlinks
</title>
</head>

<body>

<h1>
Creating HTML Hyperlinks
</h1>
<p>
It's easy to create links. We can link to Google if we'd like to complete a search!
<a href="http://www.google.com">Google</a>. Very easy!
</p>

</body>

</html>

You can copy the HTML source into your own HTML file, and you will now have a nice link
to Google so you can search the Internet. The hyperlink itself is created using the anchor
or a tag. There are a few attributes you can set but in this example all we are concerned
with is the href attribute. The value you specify inside the href attribute tells the a tag
where to send a user when she click on the link in the page.
The a tag is pretty flexible and you can use it in many ways. An interesting property of
the a tag is that it allows block level content inside of the element. Recall, block level
elements take up vertical space. Certainly text links are the most common use case of
using the a tag but we can also wrap the a tag around any sized image, or even a div
which may be taking up large amounts of vertical space. The provides a much larger
clickable surface area if you need to provide that for your users.

What Are Relative URLS?


You may have heard the term Relative URL and wondered what that means. Relative
URLs are relative because they do not specify a complete host and path. This also works
for files that are located in different directories on the server. Let’s imagine we have two
HTML files on the filesystem. In the base directory we have webpage.html and in a
directory aptly named directory, we have a file named hyperlinks.html Here is the simple
HTML for your viewing pleasure.
webpage.html
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<title>
Relative HTML Hyperlinks
</title>
</head>

<body>

<h1>
Relative HTML Hyperlinks
</h1>
<p>
We can use relative URLs to link to other resources in the same domain.
<a href="directory/hyperlinks.html">This is a relative URL!</a>
</p>

</body>

</html>

hyperlinks.html
<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8" />
<title>
This page is in a directory
</title>

</head>

<body>

<h1>
A webpage
</h1>
<p>
I'm located in the directory folder
</p>

<p>
We can link back to the original document like so. <a href="../webpage.html">Link Back!</a>
</p>

</body>

</html>

This simple code will set up links between two HTML files located in different directories
using a Relative URL format. We have a link on each page to show how you can navigate
both up and down the directory structure. When you want to navigate up, you simple
provide the name of the directory followed by a forward slash, followed by the name of the
file to link to. If you need to span multiple directories, that is easy to do as well. You simply
specify them in this format. directory/otherdirectory/hyperlinks.html. When you need
to navigate down the directory path, you can use the special ../ notation to go back one
level. If you need to span multiple directories while going back you can do so by doing
something like this ../../webpage.html.

What Is A Base URL?


When working with Relative URLs, the HTML is able to intelligently determine where the
current working file lives. From there it calculates where all the other files you link to on
that server are located. Well guess what, there is a way you can use the <base> tag to
specify what the base / root / starting point is for the relative calculations. We can modify
some of our example HTML to show you how this works. We are going to set up the
link <a href="hyperlinks.html">This is a relative URL!</a>. Now you can see we are
only linking to the file hyperlinks.html
<!DOCTYPE html>

<html lang='en'>

<head>
<meta charset="UTF-8" />
<base href="http://shell.cas.usf.edu/mccook/uwy/" />
<title>
Relative HTML Hyperlinks
</title>
</head>

<body>

<h1>
Relative HTML Hyperlinks
</h1>
<p>
Changing what the HTML will use for Relative URL Calculations can be done with the base tag.

<a href="hyperlinks.html">The base tag modified the Base URL!</a>


</p>

</body>

</html>

In this code, even though we only specified the href in the a tag as hyperlinks.html, if we
click the link, we are taken to the URL
of http://shell.cas.usf.edu/mccook/uwy/hyperlinks.html. Wow! This was possible since
we specified the base of http://shell.cas.usf.edu/mccook/uwy/ in the <base> tag. This is
a very powerful feature, but seldom used in popular web development. The reasons is that
it can lead to confusion and problems in maintaining the code as new pages are added to
your website.

HTML Page Jumps With Fragments


This is a really awesome feature of HTML and I’m sure you have run across this technique
plenty of times. Have you ever noticed that if you visit a webpage that is particularly large
and scrolls a long distance on the page, the webmaster often gives you some links that
you can click and you will be taken to very specific points in the page. This is a great way
to give users an option to get right at the content that they are interested in without having
to scan and search the page. We’ll test this out right in our page right now! All you have to
do is specify an id attribute on the element in the page you would like to jump to, then
specify that id as the href for the link you are dealing with. Just remember that on the
element you would like to jump to where you specify the id, you do not use the # sign,
however the # is required to be prepended to the id in the href of the a tag.
<ul>
<li><a href="#url">Uniform Resource Locator</a></li>

<li><a href="#chh">Creating HTML Hyperlinks</a></li>

<li><a href="#waru">What Are Relative URLS?</a></li>

<li><a href="#wiabu">What Is A Base URL?</a></li>


</ul>

• Uniform Resource Locator


• Creating HTML Hyperlinks
• What Are Relative URLS?
• What Is A Base URL?

Another popular use of this technique is to provide a fragment that the user can click at
various places in the web page to bring them back to the top of the page. It uses the same
technique. You simply place an id on an element near the top of the page, then provide a
link somewhere else that uses that id as its href value, and when the user clicks – they will
go right to the top of the page. Fun!

Creating Links With Images


It’s pretty easy to make links by using images. The end result is the same as text links, the
user will be taken to the destination upon clicking the link. Sometimes its nice for design
purposes to provide images as the basis of links in the web page. You especially see it a
lot on really design heavy websites, where a simple text links is just a little too boring
For example, we can easily link to two other pages on this website using this HTML.
<a href="http://vegibit.com/what-is-html/">Learn HTML</a>

<a href="http://vegibit.com/what-is-html/"><img src="http://vegibit.com/wp-


content/uploads/2014/06/html.png" /></a>

<a href="http://vegibit.com/getting-started-with-javascript-programming/">Learn JavaScript</a>

<a href="http://vegibit.com/getting-started-with-javascript-programming/"><img
src="http://vegibit.com/wp-content/uploads/2014/04/javascript.png" /></a>

Text Link
Learn HTML
Image Link

Text Link
Learn JavaScript
Image Link

Conclusion
Links are so common in our everyday use that we rarely even think twice about them. It
was fun to review all of the fundamentals of HTML Hyperlinks in this episode. In fact,
revisiting the page jump with fragments concept has me thinking I should implement that
technique more often!

HTML5 Data Attributes


One of the most awesome new features of HTML5 is having the ability to set
data-attributes on any element on the page. This is an incredibly powerful
feature, and you can really go wild with your imagination if you want to. The sky
is the limit. The awesome Twitter Bootstrap Framework makes heavy use of
data attributes when working with their JavaScript and jQuery plugins. So if
you’ve ever wondered what those various data- attributes are or what they do,
you are in the right place. Let’s jump right into HTML5 Data Attributes!

Data Attributes are Awesome


The addition of data attributes to HTML5 is one of the key features that enables HTML5 to
compete with native style applications in the closed platform world. Developers are no
longer building static websites with HTML, but rather full blow applications that need to run
in all sorts of different environments. Data attributes help make this a reality.

Always Starts With data-something


When you want to use data attributes in your HTML, the attribute will always begin
with data-. After the dash is where you begin your own naming convention that makes
sense for the application. If you are working with a video game application maybe you
have things like data-player data-score data-high-score and data-start-game.

Embed Any Data on Any Element


Data attributes can be assigned to any element on the page. In addition, you can store
whatever value you need in whatever data attribute you are using for the application.
Access The Data With the Dataset Object
When you assign values to the data attributes, they are inserted into the datasetobject in
JavaScript. You can then access those values in the JavaScript you write for the page and
you will see an example shortly of how to do this.

Works With Native JavaScript and jQuery


HTML5 data attributes were created with JavaScript integration in mind. In addition to
accessing this data with native JavaScript, you can also use this approach with jQuery via
the data() or attr() methods.

Data Attributes are Converted to Camel Case in JavaScript


You’ll see many times in the HTML5 that you come across that data attributes often use a
hyphenated style. Just like we mentioned the video game example that may have data-
player data-score data-high-score and data-start-game attributes, those attributes will
get converted to camel case JavaScript variables. So these examples would result in the
JavaScript variables of player score highScore and startGame. You would then access
them in JavaScript via the dataset object such
as dataset.player dataset.score dataset.highScore and dataset.startGame.

Data Attributes are Super Flexible


As you can see, data attributes are very flexible. If you’ve ever been building an application
where you dynamically generate HTML and attributes to the page, you know that you often
are setting all kinds of different values. With so much interactivity being built into websites
and applications now, we need a way to be able to grab those values from the webpage
with JavaScript and jQuery. Data attributes give us all of this and more.

HTML5 data attributes are supported in all the modern web browsers including Google
Chrome, Mozilla Firefox, and Apple Safari. Both JavaScript and jQuery work equally well
with data attributes. With these key concepts in mind, let’s take a look at some simple
markup that will show these ideas in action.

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8" />
<title>
Working With HTML5 data attributes
</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="jquery-1.11.1.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {

// accessing data- attributes with jQuery


$('a.btn').click(function () {
var myAttribute = $(this).attr('data-my-attribute');
$('#content').after('<div class="alert alert-info"><h3>' + myAttribute + '</h3></div>');
})

});

// accessing data- attributes with native JavaScript


function answer(evt) {
game = evt.dataset.videoGame;
status = evt.dataset.gameStatus;
time = evt.dataset.gameTimeFrame;
var newlyCreated = document.createElement('h2');
newlyCreated.innerHTML = game + status + time;
var native = document.getElementById('native');
native.appendChild(newlyCreated);
}
</script>
</head>

<body class="container">

<h1>
Working With HTML5 data attributes
</h1>
<p class="lead">
You can specify your own data attributes on your tags in the page. This is super useful for placing
data dynamically into the HTML via a server side technology, then accessing those values by grabbing
them with JavaScript.
</p>
<a class="btn btn-primary btn-lg btn-block" href="#" data-my-attribute="BOOM!">Click, Click</a>.
<div id="content"></div>

<button class="btn btn-success btn-lg btn-block" data-video-game="Super Mario Brothers " data-game-
status="is the greatest " data-game-time-frame="of all time!" onclick="answer(this)">
Click to Learn the Greatest Video Game of All Time!
</button>
<div id="native"></div>

</body>

</html>
Cool!This was a super simple nonsense example, but it gets the point across. For the first
example, we have a button on the page, with some jQuery set up that will act when the
button is clicked. When we click the button, jQuery fetches the value of the data attribute in
question and places that value into the myAttribute variable. Then using jQuery, we simply
insert a snippet of HTML after the empty content div in the HTML and include the value
of myAttribute in the output.
For the second example we use native JavaScript to accomplish a similar effect. This
example shows how multiple data attributes assigned to the same element are handled.
Basically, all of the various data attributes get auto converted to camel case and placed
into the dataset object. In the HTML, we simply attach an onclick event and run the
function answer when the user clicks to find out what the greatest video game of all time is.
Inside our function we set up three variables and assign their values using the data we
were able to access from the three different data attributes that were a part of the element
on the page. We then use native DOM functions to assemble a new element and manually
append the element to the div on the page. Thanks goodness for jQuery

HTML Form Tutorial


Forms are a really important aspect of HTML. It is through the use of Forms
that we can accomplish interactivity and data collection from the user. There
are many different ways to implement forms and the various form elements that
go along with them when you are creating your web pages or web applications.
This episode will take a close look at the ones you are most likely to be using or
maintaining in your various projects. Let’s jump right in to the wonderful world of
HTML Forms!

The HTML <form> Tag


We can get this party started with the The HTML <form> Tag, for without it, none of the
other elements we will soon discuss are going to have much meaning for you! HTML
Forms are typically used to send data to a server side technology like PHP for processing.
You can also use JavaScript to process form data in the client, and that is becoming quite
popular as well. The HTML <form> Tag is a container of sorts so that you can place
elements like Radio Buttons, Text Areas, Input fields and more for data collection inside of
it. The syntax looks like so:
<form>

<-- place input elements in between the form tags -->

</form>

We would take a look at how this renders in the browser, but the form itself is actually not
displayed in the browser. It is only the elements within the form that display, and we’ll take
a look at some of them now.
<input type="text">
Text fields for input are used to give the user a one line field to enter text. They are quite
common, and this is an example of the syntax to create one.
<form>
Website: <input type="text" name="website"><br>
Computer: <input type="text" name="computer">
</form>

This HTML renders in the browser like so


Website:
Computer:
You’ll notice the name attribute in the source code here. This is a very important attribute! It
is by this attribute that you can access data collected to the form in your server side code.
You will see exactly how this works shortly.

<input type="password">
An input can also have a type of password. This input essentially works the same as
type text, but the browser will obscure the input text by making the characters you type
invisible by turning them into small circles or asterisks. In addition, when you submit the
form, the browser will usually ask you if you would like to have your password
remembered. This is all due to setting the type to password. This is some HTML that
denotes an input with it’s type set to password.
<form>
Password: <input type="password" name="password">
</form>

This is how it displays in the browser.


Password:

<input type="checkbox">

The checkbox seems simple enough. Then you learn about Radio Buttons There is
sometimes some confusion between the two, since they both look pretty similar in the
browser with the exception that checkboxes come in the shape of a small box, while radio
buttons look more like a small circle. Each of them share the trait of being able to be
selected by the user. They seem so alike, so what gives?! The main idea is
that checkboxes are used for one or many choices. Say you provided a list of four
seasons to the user. With the checkbox option, the user could select just one, or all of the
seasons. With the radio button option, the user would only be able to select her favorite.
The HTML looks like this.
<form>
<input type="checkbox" name="season" value="spring"> Spring<br>
<input type="checkbox" name="season" value="summer"> Summer<br>
<input type="checkbox" name="season" value="fall"> Fall<br>
<input type="checkbox" name="season" value="winter"> Winter
</form>

This HTML displays in the browser like so.


Spring
Summer
Fall
Winter

<input type="radio">
Now that you see how checkboxes work, it is the perfect time to observe how Radio
Buttons work! Like we explained above, a collection of checkboxes provides the user the
ability to select one or many options. The radio button is different in that the user can only
select one. We can redo the above HTML and simply change the type to radio. Observe.
<form>
<input type="radio" name="season" value="spring"> Spring<br>
<input type="radio" name="season" value="summer"> Summer<br>
<input type="radio" name="season" value="fall"> Fall<br>
<input type="radio" name="season" value="winter"> Winter
</form>

This HTML displays in the browser like so.


Spring
Summer
Fall
Winter
To hammer the point home, try to select all of the seasons in both scenarios above. What
was the result?
<textarea>
We now get into some HTML form elements that are their own being, that is to say they do
not have a type! All of the examples above are of various inputs, and what determines how
they work is the type that they are assigned. The <textarea> tag is the first such one we’ll
take a look at. The <textarea> tag is used to provide a larger surface area to place text
into than the one line <input type="text"> provides.<textarea> has attributes of
both rows and cols so that you can specify the size of the <textarea> Let’s take a look.
<form>
<textarea rows="5">
This is a beautiful textarea, provided courtesy of http://www.vegibit.com. Type away in here and see
how I work.
</textarea>
</form>

<select>
The <select> tag is used to provide a drop down list to the user. Inside of
the <select> tag, you place <option> tags to contain each different possible selection.
The <select> tag is a single choice selection scenario by default. You can change this to a
multiple selection by adding [] brackets to the end of the name attribute and setting the
multiple attribute. You can hold down the Ctrl in windows and the Command button on a
Mac in order to select more than one option.
<form>
<select name="select2[]" multiple="multiple">
<option>Chinese</option>
<option>Mexican</option>
<option>Italian</option>
<option>Thai</option>
<option>Seafood</option>
<option>Indian</option>
<option>Mediterranean</option>
</select>
</form>

Chinese
<datalist>
The <datalist> tag is pretty slick in that it provides a type of auto complete functionality as
the user begins to type. The auto completion is done by checking what the user types
against all of the values provided for each option. The closest match will auto populate
when the user begins typing. The list attribute of the associated input element is what
binds the datalist and input together.
<input name="days" list="days">
<datalist id="days">
<option value="Sunday">
<option value="Monday">
<option value="Tuesday">
<option value="Wednesday">
<option value="Thursday">
<option value="Friday">
<option value="Saturday">
</datalist>

<input type="submit">
The Mac Daddy, The Big KaHuna, The Stud to rule them all – it is our trusty <input
type="submit"> button. At the completion of your form, you are going to need a way to
actually take all of the collected data and send it on over to the server for some
processing. You do this of course with the Submit Button. When the user clicks the Submit
Button in your form, the data which was collected will be sent to a specific server side page
based on the action attribute which was set in the opening <form> tag. This data can be
passed via GET or POST. We’re focusing on POST in this episode. There are countless ways
to style the submit button, but the actual HTML to enable this to happen looks something
like this:
<form name="input" action="process.php" method="post">
Website: <input type="text" name="website">
<input type="submit" value="Submit">
</form>

Create Your HTML Form


Now that we have covered several important features of HTML Forms, we can go ahead
and build one as an example for collecting data. Let’s go ahead and build a form that will
put all of these concepts to use. First we’ll use an <input type="text"> to capture an email
address. Then we’ll insert a couple of <input type="checkbox"> to show how
checkboxes work. After that, we’ll add a nice <textarea> to show how you can have a
multi-line area for typing text. Next comes a dropdown menu by way of the <select> tag so
the user can choose the best basketball player of all time. Once this is done, we’ll need to
allow the user to choose their favorite foods using the <select multiple> tag. Before we
submit, we’ll provide one last option to chose the best day of the week and use
the <datalist> to give some auto complete magic as well. Here is the code to do it!
form.html
<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8" />
<title>Using HTML Forms For Data Collection</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
<script src="jquery-1.11.1.js"></script>
<script>
$(document).on('submit', 'form.form-horizontal', function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $('form').serialize(),
success: function (data) {
$('#results').append(data);
},
error: function (xhr, err) {
alert('Error');
}
});
return false;
});
</script>
</head>

<body class="container">
<div id="form">
<h2> Using HTML Forms For Data Collection <small>Any element you want to collect data from in a
form must have a <code>name</code> property. The <code>name</code> becomes the key name of the
associative array once the form is submitted.</small></h2>
<form class="form-horizontal" action="print_r_post.php" method="post">
<fieldset>
<div class="form-group">
<div class="col-xs-12">
<input name="textinput1" class="form-control" id="inputEmail" placeholder="Email" type="text">
<span><strong><input></strong> of type <code>text</code></span>

</div>
</div>

<div class="form-group">
<div class="col-xs-12">
<input name="textinput2" pwfprops="," class="form-control" id="inputPassword"
placeholder="Password" type="password">
<span><strong><input></strong> of type <code>password</code></span>

<div class="checkbox">
<input name="checkbox1" type="checkbox">
<span><strong><input></strong> of type <code>checkbox</code></span>

</div>
<div class="checkbox">
<input name="checkbox2" type="checkbox">
<span><strong><input></strong> of type <code>checkbox</code></span>

</div>
</div>
</div>

<div class="form-group">
<div class="col-xs-12">
<textarea name="textarea" class="form-control" rows="3" id="textArea"></textarea>
<span><strong><textarea></strong> is not an <strong><input></strong> and has no type</span>

</div>
</div>
<div class="form-group">

<div class="col-xs-12">
<div class="radio">
<input name="radioOptions" id="optionsRadios1" value="option1" type="radio">
<span><strong><input></strong> of type <code>radio</code></span>

</div>

<div class="radio">
<input name="radioOptions" id="optionsRadios2" value="option2" type="radio">
<span><strong><input></strong> of type <code>radio</code></span>

</div>

</div>
</div>

<div class="form-group">

<div class="col-xs-12">
<select name="select1" class="form-control">
<option>Jordan</option>
<option>James</option>
<option>Bird</option>
</select>
<strong><select></strong> is not an <strong><input></strong> and has no type
<br>

<select name="select2[]" multiple="" class="form-control">


<option>Chinese</option>
<option>Mexican</option>
<option>Italian</option>
<option>Thai</option>
<option>Seafood</option>
<option>Indian</option>
<option>Mediterranean</option>
</select>
<strong><select></strong> with the <code>multiple</code> attribute allows multi selections

</div>
</div>

<div class="form-group">

<div class="col-xs-12">
<input name="days" class="form-control" list="days">
<datalist id="days">
<option value="Sunday">
<option value="Monday">
<option value="Tuesday">
<option value="Wednesday">
<option value="Thursday">
<option value="Friday">
<option value="Saturday">
</datalist>
<strong><datalist></strong> provides autocomplete as you begin typing

</div>

</div>

<div class="form-group">
<div class="col-xs-12">
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>

<div class="bg-info" id="results"></div>

</body>

</html>

print_r_post.php
<pre class="bg-info">
<h3>
<?php
print_r($_POST);
?>

This is an example of Rick James filling out all of the information in our form. Dealing with
the server side processing of all of this data is beyond the scope of this episode, but a
good thing to include here is an example of being able to view the raw data that gets
submitted. We use just a small piece of JavaScript to do this by sending the data via AJAX
to the print_r_post.php file on the server using jQuery. This PHP file does nothing more
than to print recursively all of the data that gets sent to it. That data then gets inserted into
the page, again using jQuery. The code to make it happen is right here.
$(document).on('submit', 'form.form-horizontal', function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $('form').serialize(),
success: function (data) {
$('#results').append(data);
},
error: function (xhr, err) {
alert('Error');
}
});
return false;
});

You can run this code in your own local development environment as well. The output
when we click the submit button here should result in the following getting inserted into the
page.

Awesome!Being able to dump this form data to an array makes it easy to troubleshoot and
debug any form problems you may run across during your web development
adventures
As an added bonus, now that you are a pro in creating awesome forms in HTML, you can
also read up on PHP Form Processing so that you can do whatever you like with the data
you are able to collect!
HTML Encoding With htmlspecialchars and
htmlentities

In the last episode of this PHP Tutorial Compilation, we looked at working with
Links and URLs and how sometimes, special characters will wreak havoc upon
our HTML. These problems can at least break a link, or at worst, expose a
vulnerability to malicious intent via the goblins of the internets which wish to
bring malice to your web application. It turns out, it is not only our URLs that we
must protect and encode. We also need to be aware of the large collection of
special characters that may appear in the text of your HTML. For this, we also
have convenient ways to encode and protect our markup so as to be sure your
website remains upright, intact, working smoothly, and most of all being the
awesome presence that it is. Let’s do this!

HTML Encoding With PHP


HTML is the markup language of the web, and when it comes down to it, it is the HTML
that makes the web tick. All of these fancy programming languages are fun to use in order
to facilitate dynamic pages and so on, but without HTML, we wouldn’t have too much now
would we? One of the most common things we do with PHP, or any other web based
programming language for that matter, is to generate HTML on the fly using logic and
conditions. As we know, HTML makes use of angle brackets and other characters to
provide a means to the browser to render a web page. HTML has some special reserved
characters that you need to watch out for since they have a specific meaning to HTML.
< and >
Here they are, the < and > characters. These two characters are what surround the html
tag names in the page. This is what instructs the browser that hey, something really
interesting is happening here and you need to interpret the information between these tags
as such. These angled brackets also denote that the data within them is not to be
outputted to the page in human readable form. Though the web browser sees something
like <b>this bold text</b>, the user should see this bold text. Two different encoding
styles with two different meanings.

HTML Reserved Characters


There are four main characters that are reserved in HTML which we need to pay close
attention to. Here is a table that outlines them all.

Character Encoding

< &lt;

> &gt;

& &amp;

" &quot;
What this means is that when you would like your users to see the literal character, you
need to provide the coded version. Maybe you would like to say something like Twitter is
greater than Facebook, and use the greater than sign. In the actual html will be Twitter is
&gt; Facebook, however the user will see the actual Twitter is > Facebook displayed. If
this or any of the other reserved characters are not properly encoded, you run the risk of
causing your page to not display to the user.

htmlspecialchars($string)
First up we’ll examine the use of htmlspecialchars. It might make sense to observe a
broken scenario, and then we’ll look at the solution using htmlspecialchars. Suppose we
want to include a link with specific anchor text. The anchor text we’d like to display
is <Click Here> & Prosper! So you figure, ok easy enough, we can just place this text we
like in between anchor tags and create our link. Let’s try it.
<html>
<head>
<meta charset="utf-8">
<title>HTML Encode Like a PRO</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

<a href="http://localhost/bootstrapsandbox/encode.php">
<Click Here> & Prosper!
</a>

</body>
</html>

& Prosper!
Do you see what that is right there? That right there, is a bit fat fail. The page didn’t display
the text we wanted at all. The reason for this is because the browser comes along and
sees those angled brackets and thinks that it is dealing with an HTML tag. In this case
however, it is not HTML at all. It is the actual angled brackets that we want the user to see
in the text of the link. It is times like this that htmlspecialchars comes to the rescue!
Observe!
<html>
<head>
<meta charset="utf-8">
<title>HTML Encode Like a PRO</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

<a href="http://localhost/bootstrapsandbox/encode.php">
<?php echo htmlspecialchars('<Click Here> & Prosper!'); ?>
</a>

</body>
</html>
<Click Here> & Prosper!
Nice!Now that link text is working as designed. Think of the htmlspecialchars as a method
to disable HTML so to speak. It disables the HTML to the browser and allows the user to
see what the browser normally sees. A key point of note is that htmlspecialchars only
handles the four reserved characters listed in the table above. Now you may know that
there are a rather large collection of symbols that we might want to display in the text of
our HTML which the browser will not know how to render. Things like Trademark symbols,
Copyright Symbols, At signs, and many more. In this case, you need to bust out the big
dog, the htmlentities function.

htmlentities($string)
The htmlentities function covers all characters that have an equivalent html entity
representation in the language. Therefore, htmlentities is much more powerful. To illustrate
this, we’ll try to enter in some of the more common special characters that you might want
to have in your webpage. Let’s try it out.
<?php
$text = '© ® ™ £ € ¥';
echo $text;
?>

This might display on some devices, however you may get just a string of really strange
hieroglyphic looking type characters. To be safe, you should wrap any text that has special
characters into the htmlentities function like so.
<?php
$text = '© ® ™ £ € ¥';
echo htmlentities($text);
?>

©®™£€¥

URL Encoding Meets HTML Encoding


It’s time to level up friends. Now that we have a good grasp of URL encoding from our last
episode, as well as the fundamentals of html encoding via this action packed tutorial, we
can put the whole picture together to see how this works. This will sum up our learning of
URL as well as HTML encoding.
<html>
<head>
<meta charset="utf-8">
<title>HTML Encode Like a PRO</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>
<?php
$page = 'bootstrapsandbox/encode.php';
$variable1 = 'Look out now, < > " and & which are bad!';
$variable2 = 'More bad chars like &#?*$[]+ and so on!';
$anchortext = '<Click Here> & Prosper!';

$url = 'http://localhost/';

// rawurlencode anything to the left of the ? !!


$url .= rawurlencode($page);

// urlencode anything to the right of the ? !!


$url .= '?' . 'variable1='. urlencode($variable1);

$url .= '&' . 'variable2='. urlencode($variable2);

// at this point $url is safe to put into the query string


// it might NOT however, be safe to output into our HTML!

// Just becuase a string is now fully URL encoded does not mean
// it is safe for output into page HTML. This is why the $url
// parameter must also be run through htmlspecialchars.
?>
<a href="<?php echo htmlspecialchars($url); // ?>">
<?php echo htmlspecialchars($anchortext); ?>
</a>

</body>
</html>
http://localhost/bootstrapsandbox%2Fencode.php?variable1=Look+out+now%2C+%3C+%3E+%22+and+%26+which+
are+bad%21&variable2=More+bad+chars+like+%26%23%3F%2A%24%5B%5D%2B+and+so+on%21

The result is a nicely encode URL with and special characters or entities accounted for
which is epic!

Handy HTML Entity Table


If you ever need a good reference for all of the HTML entities you can use, here is a list of
them. This list is good for being aware of characters that should be run through the
htmlentities function as well.

Various ASCII Character entities.


Symbol Encoding
À &Agrave;

Á &Aacute;

 &Acirc;

à &Atilde;

Ä &Auml;

Å &Aring;

Æ &AElig;

Ç &Ccedil;

È &Egrave;

É &Eacute;

Ê &Ecirc;

Ë &Euml;

Ì &Igrave;

Í &Iacute;

Î &Icirc;

Ï &Iuml;
Ð &ETH;

Ñ &Ntilde;

Ò &Ograve;

Ó &Oacute;

Ô &Ocirc;

Õ &Otilde;

Ö &Ouml;

Ø &Oslash;

Ù &Ugrave;

Ú &Uacute;

Û &Ucirc;

Ü &Uuml;

Ý &Yacute;

Þ &THORN;

ß &szlig;

à &agrave;

á &aacute;

â &acirc;
ã &atilde;

ä &auml;

å &aring;

æ &aelig;

ç &ccedil;

è &egrave;

é &eacute;

ê &ecirc;

ë &euml;

ì &igrave;

í &iacute;

î &icirc;

ï &iuml;

ð &eth;

ñ &ntilde;

ò &ograve;

ó &oacute;

ô &ocirc;
õ &otilde;

ö &ouml;

ø &oslash;

ù &ugrave;

ú &uacute;

û &ucirc;

ü &uuml;

ý &yacute;

þ &thorn;

ÿ &yuml;

Various ISO-8859-1 HTML entities.

Symbol Encoding
&nbsp;

¡ &iexcl;

¢ &cent;

£ &pound;

¤ &curren;
¥ &yen;

¦ &brvbar;

§ &sect;

¨ &uml;

© &copy;

ª &ordf;

« &laquo;

¬ &not;

&shy;

® &reg;

¯ &macr;

° &deg;

± &plusmn;

² &sup2;

³ &sup3;

´ &acute;

µ &micro;

¶ &para;
¸ &cedil;

¹ &sup1;

º &ordm;

» &raquo;

¼ &frac14;

½ &frac12;

¾ &frac34;

¿ &iquest;

× &times;

÷ &divide;

HTML entities for Math Symbols.

Symbol Encoding

∀ &forall;

∂ &part;

∃ &exist;

∅ &empty;

∇ &nabla;
∈ &isin;

∉ &notin;

∋ &ni;

∏ &prod;

∑ &sum;

− &minus;

∗ &lowast;

√ &radic;

∝ &prop;

∞ &infin;

∠ &ang;

∧ &and;

∨ &or;

∩ &cap;

∪ &cup;

∫ &int;

∴ &there4;
∼ &sim;

≅ &cong;

≈ &asymp;

≠ &ne;

≡ &equiv;

≤ &le;

≥ &ge;

⊂ &sub;

⊃ &sup;

⊄ &nsub;

⊆ &sube;

⊇ &supe;

⊕ &oplus;

⊗ &otimes;

⊥ &perp;

⋅ &sdot;

Greek Letters and their HTML Entities.


Symbol Encoding
Α &Alpha;

Β &Beta;

Γ &Gamma;

Δ &Delta;

Ε &Epsilon;

Ζ &Zeta;

Η &Eta;

Θ &Theta;

Ι &Iota;

Κ &Kappa;

Λ &Lambda;

Μ &Mu;

Ν &Nu;

Ξ &Xi;

Ο &Omicron;

Π &Pi;
Ρ &Rho;

Σ &Sigma;

Τ &Tau;

Υ &Upsilon;

Φ &Phi;

Χ &Chi;

Ψ &Psi;

Ω &Omega;

α &alpha;

β &beta;

γ &gamma;

δ &delta;

ε &epsilon;

ζ &zeta;

η &eta;

θ &theta;

ι &iota;

κ &kappa;
λ &lambda;

μ &mu;

ν &nu;

ξ &xi;

ο &omicron;

π &pi;

ρ &rho;

ς &sigmaf;

σ &sigma;

σ &sigma;

τ &tau;

υ &upsilon;

φ &phi;

χ &chi;

ψ &psi;

ω &omega;

ϑ &thetasym;

ϒ &upsih;
ϖ &piv;

Other Various HTML entities.

Symbol Encoding
Π&OElig;

œ &oelig;

Š &Scaron;

š &scaron;

Ÿ &Yuml;

ƒ &fnof;

ˆ &circ;

˜ &tilde;

– &ndash;

— &mdash;

‘ &lsquo;

’ &rsquo;

‚ &sbquo;

“ &ldquo;
” &rdquo;

„ &bdquo;

† &dagger;

‡ &Dagger;

• &bull;

… &hellip;

‰ &permil;

′ &prime;

″ &Prime;

‹ &lsaquo;

› &rsaquo;

‾ &oline;

€ &euro;

™ &trade;

← &larr;

↑ &uarr;

→ &rarr;

↓ &darr;
↔ &harr;

↵ &crarr;

⌈ &lceil;

⌉ &rceil;

⌊ &lfloor;

⌋ &rfloor;

◊ &loz;

♠ &spades;

♣ &clubs;

♥ &hearts;

♦ &diams;

Html Tutorials For Beginners


In this roundup of Html Tutorials For Beginners we have a nice collection of
some really fantastic links and resources to get you up to speed with HTML.
There are so many specifics to working with HTML, that it helps to have a nice
list such as this one that you can refer back to from time to time. Whether you
have a question about how an image is set to align with nearby text, or if you
should try using tables versus divs in a specific use case, this collection has
you covered. Let’s take a look at some of them now.
• http://vegibit.com/html/

You can begin with a great collection of HTML


tutorials right here at VegiBit! We cover all of the fundamentals, text features, image
manipulation, hyperlinks, data attributes, forms and more. Once you have all of this
down, move on to the rest of the great resources listed below.

• http://www.sitepoint.com/-html-css-beginners-guide/

Sitepoint has been around for web design and


development since the early days of the web. As such they have some fantastic
resources amassed you can tap into. This particular tutorial which covers HTML and
CSS was first published in 2009! It’s an oldie but goodie however, and a great spot to
get your beginning HTML and CSS chops up to speed.
• http://www.htmlgoodies.com/-primers/html/article.php/3478131

HTML goodies has the goodies you need to


supplement your learning. This one starts right with the basics and will have you
working with tags, manipulating text, linking pages, embedding images, and much
more. Beyond HTML, there are all kinds of other goodies to be had as well, so do
check them out.

• http://www.quackit.com/-html/tutorial/

Quack it has a great tutorial for beginners to


HTML. They focus on starting with the basics and take you through everything you’ll
need to make your own webpages. All of the main points are covered such as
templates, layouts, images, tables, forms, comments, tags, links, colors, and more.

• http://www.skilledup.com/-articles/free-beginner-html-tutorials/
Get your skills up with a great collection of
HTML resources from skilled up! In this article skilled up assembles 20 of the best
HTML tutorials for beginners. Check them out to see who they put in the top 20.

• http://html.net/-tutorials/html/

If you’re learning HTML, it makes sense to


bookmark html.net. Like most other resources in our list, they cover HTML from A to
Z, and break everything down into a fantastic 15 part series of lessons.

• http://www.htmldog.com/-guides/html/beginner/

HTML Dog will have you hitting the ground


running with their awesome collection of tutorials for beginners to HTML. This series
takes the approach that you are a complete noob, and will need careful guidance.
Sound like you? Then go check them out!

• http://learn.shayhowe.com/-html-css/

I really like the layout of this site with its


beautiful use of colors and geometry. Based on what this site looks like, you will be
learning some best practices. In addition, this HTML and CSS tutorial also comes in
book form if you’d rather dig in that way.

• http://www.w3schools.com/-html/default.asp

W3 schools has a large collection of tutorials to


learn HTML. The courseware is broken down in a chapter by chapter basis, along
with examples you can try for yourself during each step of the way. Tags, entities,
attributes, color names, language codes, encoding, and more are covered.

• http://www.html-5-tutorial.com/
It’s just like they say, “It’s not rocket science!”
At least the folks over at HTML 5 Tutorial think so. To be fair, unless you are really a
complete and total beginner, writing HTML really isn’t rocket science. Add this one to
your list of great resources.

• http://www.codecademy.com/-tracks/web

Take your learning to the next level with


HANDS ON coding right in your browser. The HTML and CSS tract at Codecademy
boasts 4.5 million students and a full seven hours of estimated course time for the
series. Learn everything all of these resources on this page teach you, live and in the
browser. It’s truly fantastic.

• https://www.khanacademy.org/-computing/computer-programming/html-css
One of the best free learning resources
available to mankind today is the great Khan Academy. Lucky for us web developers,
they have a fantastic course for HTML and CSS.

• http://teamtreehouse.com/-library/html

Team Treehouse is another high quality


destination to learn everything you need to know about HTML. Get your Hyper Text
Markup Language skills down cold.

• http://www.html5rocks.com/en/

If rock and roll is your thing, and why wouldn’t it


be, then you point yourself right at HTML 5 Rocks. HTML 5 Rocks has a very large
collection of articles that cover things you didn’t even know exist yet in HTML for
when you’re ready to move past beginner status.

• http://thecodeplayer.com/

At The Code Player, you can take a unique


approach to learning HTML, CSS, JavaScript and more. The Code Player
showcases walkthroughs in a video format that shows cool things getting created
from scratch. How cool is that?

• https://developer.mozilla.org/-en-US/Learn/HTML

Mozilla is a powerhouse in the open source


world. The Mozilla Developer Network has some fantastic resources for learning
about HTML, or for exhaustive reference material for HTML. Whether you need that
step by step approach, or simply need to confirm a certain attribute of the language –
you can’t go wrong.
Html Tutorials For Beginners Summary
This is a great collection of resources for any aspect of learning HTML. In fact some of this
list of Html Tutorials For Beginners is kind of like a meta resource, a resource of resources!
Thanks for checking it out.

Chapter 2: PHP
What is PHP?

Now that we’ve just finished a great collection of Tutorials about WordPress, it’s
time to dig into PHP. Why dig into PHP? Well we talked a little bit about all of
the open source software packages that make WordPress possible, but what
we didn’t mention is that the majority and bulk of the program is written in PHP.
With WordPress powering almost a full twenty percent of websites worldwide,
and PHP being the language WordPress is written in, we really ought to have a
good understanding of PHP and how it works! PHP stands for PHP Hypertext
Preprocessor. It actually originally stood for Personal Home Page Tools, which
does seem to be a little easier to digest than the current PHP Hypertext
Preprocessor, but I think we’ll be ok! So without further ado, it’s time for
Random Bits of Awesomeness in PHP!

Server Side Scripting Language


PHP is a server side scripting language. What does this mean? Well, we had a good look
at how JavaScript works in a prior tutorial, and we know that JavaScript runs in a Web
Browser in most cases. PHP lives on a server, and it’s code executes on that server. Only
the result of PHP output makes it to your browser, unlike how actual JavaScript can be
delivered over a network to your Browser so it can execute.

What is a Script vs a Program


A computer program and a computer script are similar, yet there are very important
differences. Let’s take a look at a few of the differences between the two.
Script
A script typically triggers in response to an event. In the case of PHP, the event is the
action of a user requesting to view a webpage with their web browser. This is what sends
an HTTP request to the server, and triggers the execution. Once the script starts to run, it
does so from top to bottom in a very linear fashion. This happens quickly and with no user
interaction. Once this process is complete, the script shuts down so to speak until another
request is made.
Program
Programs are much different. You are probably more familiar with computer programs than
you are with scripts. A program is launched, and then it continues to run without the need
for additional requests being made. It also may jump around within the code as the
software runs depending on user interaction, unlike the top to bottom nature of a script. For
example, you likely are familiar with Microsoft Word or Microsoft Excel. These are
computer programs that when launched, continue to run and wait for user input, then take
action on the input provided.
Blurred Lines
Much like Robin Thicke, the distinction between a script and a program can begin to have
blurred lines. That is to say, as scripts become more complex, especially when you’re
talking about high level frameworks and development environments, they begin to closely
resemble the nature of a true computer program. So what’s the big deal you say? Well, it’s
not a big deal really. It just helps to remember PHP’s humble beginnings as compared to
where it stands today in all of its modern object oriented design glory.

What does Server Side mean?


When we say server side, we mean the actual code is installed on a remote server. The
only environment under which that code can execute is on that very server. It’s in many
ways much safer than JavaScript. <flamesuit> JavaScript has it’s place, and contrary to
the Node.js fans among the populous, it is not on the server! </flamesuit>. PHP is
designed to work with HTML. You can embed PHP inside of HTML, or use PHP to
generate HTML to be sent across the network to a users web browser. Files use a .php
extension to tell the server that there is PHP code contained within the file that must be
interpreted and executed. The syntax is a derivative of the C Family of languages. In fact
the PHP engine itself is written in C, which is for all intents and purposes, the de facto
language of all of computer science. PHP is very flexible and can be arranged in a super
disciplined and clean style as is the case with modern frame works, or it can be intertwined
like Spaghetti into your HTML to create various effects. The only limit is your imagination,
so get your favorite imagination stimulant ready.

The Glorious History of PHP


If you’ve ever listened to any of the great Douglas Crockford’s lectures on JavaScript,
you’ll know that Doug likes to talk about the entire spectrum of computers and computer
science all the way back to Grace Murray Hopper who was born on December 9, 1906.
Grace is credited with being a true pioneer in computer science. It is always fascinating to
listen to experts in the field discuss history and travel through time so to speak to arrive at
where we are today. In the case of PHP, it’s life began in 1994 at the hands of a genius
named Rasmus Lerdorf. Rasmus used the C Programming language to create the the very
first iteration of PHP, and C is still what powers the PHP engine today. Early on, PHP was
quite limited but by 1998 Andi Gutmans and Zeev Suraski joined the project and rewrote
the PHP engine for version 3 of the language. It was also at this time that the naming
convention of PHP changed from that of Personal Home Page tools to PHP: Hypertext
Preprocessor. Some say this was the point at which we should have begun to fear PHP,
when these guys decided to make use of a recursive acronym to describe their creation.
Fear not! PHP is awesome, no matter what we call it. Fast forward to the Y2K, and PHP
had another major overhaul. This is when Andi Gutmans and Zeev Suraski formed Zend,
the PHP Company. They rewrote the engine again, and began to incorporate more
modern techniques, and the beginnings of OOP or Object Oriented Programming
techniques into the language. PHP 5 came out in the year 2004, and it is from this version
that the modern iterations of PHP that we will discuss here are derived. PHP is now a
modern and powerful scripting language, and we’ll learn all about it as we tackle the ins
and outs of how to use it.

The Use Case for PHP


As you began your adventure as a web developer, you learned HTML, and while it was
great to learn how to create files and place them on a server for others to view with a web
browser, you began to see the limits of this approach. HTML is static, you can’t embed
logic or behavior into HTML. Along comes PHP to the rescue.

• PHP is Open Source PHP is open source software which means you are free to
download it, use it, modify it, or otherwise do whatever you want with it. There are no
license fees or restrictions to worry about, and did we mention, it is free.
• PHP is cross platform PHP will run on Windows, Linux, OSX, or any other flavor of
UNIX you can think of. You are not restricted to a proprietary platform with restrictive
lock in.
• PHP is Powerful and Scalable PHP is simple enough to build a super basic website
for your small company website or blog. It will also scale to power multi billion dollar
companies like Yahoo and Facebook, both of which rely on PHP to support their
infrastructure. Many of the very most visited high traffic websites in the entire world
run on PHP.
• Made for the Web PHP was built for the web. The internet and world wide web rely
on many different protocols and aspects of the IP stack to run. PHP has support built
right in for dealing with HTTP hyper text transfer protocol, FTP file transfer protocol,
DNS domain name system, Streams, Sockets, and more. PHP was built for the
internet.
• Object Oriented PHP now has full support for the full range of Object Oriented
techniques available. That means you can use namespaces, classes, objects,
inheritance, control visibility, and use any of the tried and true design principles of
computer science.
• Best Documentation in Town The PHP documentation is arguably the best
language documentation available for any of the modern languages. Every single
function available is clearly documented, with community comments included for
each function. These comments will be invaluable to you as you learn since many
people before you have probably struggled with and solved whatever question you
may have. You’ll find the code snippets to be super helpful.
• Huge Development Community There are over 20 million websites on the internet
that run PHP. That’s a lot of websites, and a lot of software developers that wrote all
of the PHP to run those sites. Any problem you come across has most likely already
been solved, all you have to do is learn how the language works, and learn to
implement the code available to you. Once you have this skill, you can then make
small tweaks and modifications to the code to make things work exactly as you’d like
them to. It’s all very fun!
Powered by PHP

Getting Started with PHP


As we go through this PHP tutorial series, we’ll make every effort to cover the
fundamentals of the language soup to nuts. These next articles are not for the advanced
programmers out there, unless they want to come back and refresh the basics. In many
ways, it’s the basics and the fundamentals that are the most fun to learn. So moving
forward, we’ll have a lot of ground to cover. We’re going to need to get PHP installed in
some way shape or form so that we can begin working with the language. We’ll set up
some really cool testing tools so you can quickly test out the snippets and make your own.
Once we have a bit of a foundation, we’ll start looking at all of the features of the language.
Topics to cover include Data Types, Control Structures, Expressions, Logical Operators,
Loops, Functions, Debugging, Forms, Sessions, Cookies, MySQL Database Basics, and
more.
The What is PHP Summary
This was a fun crash course on the history of PHP and how we can begin to learn about it
and leverage the language for our own projects. With over 20 million websites already
using PHP, you’ll be in good company learning about the language as well.

PHP Code Structure

PHP is a fun language to work in for both beginners and professionals alike. In
this PHP Tutorial Series, we’re starting at the ground floor of working with PHP.
It’s really awesome to start from the beginning even for more experienced
developers that need a refresh. Many times, you’ll find advanced problems
often come back around to being very basic missteps. This is what makes the
basics so very important. They are the foundation that you will build your entire
programming knowledge base on. So now that we have taken a look at what
PHP is and the history of this sometimes controversial language, let’s start
getting our hands dirty with PHP. In this episode we’ll take a look at some of the
very basics of the language as well as the request lifecycle and where PHP fits
in to that. Much of these snippets of information are simply bread and butter
basics that we need to know before we go all ninja on ourselves. Let’s get
started!

Placing PHP in your Web Page


The primary way to use PHP is to embed it within an HTML page. There are two things to
know about placing PHP inside of your HTML files. We know that when a user makes a
request of a website, it is using HTTP to fetch an HTML file. The web server in turn sends
the file to the end user and their web browser interprets that HTML and renders a web
page for viewing. This is entirely static. To begin to make things dynamic, let’s add some
PHP.
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to PHP</title>
</head>

<body>

<?php
echo 'This text comes from PHP!';
?>

</body>
</html>

<?php and ?>


The <?php and ?> are the opening and closing tags of PHP. This is what tells the web
server to stop reading the contents of the file as static HTML, and to begin reading the
contents as PHP. Recall this goes in a top down sequence and when there is no longer
any PHP to interpret by the web server, we add a closing tag to indicate that we are back
to HTML.

Files Must have a .PHP Extension


Any files that live on your web server must have the .php extension in order to use PHP
within the page. Files of this type can have native HTML and PHP code mixed together as
long as you are making use of the opening and closing PHP tags.
Alternate Tag Styles
There are alternate tag styles available to you to denote the opening and closing locations
of PHP within your files. Be advised however, that if you use them, you may find yourself
the target of the PHP police as most of these are bad form. Here are two of the other
styles you can use.
Short Open Tags – <? and ?> as well as <?= and ?> – This is a bad idea.
ASP Style Tags – <% and %> as well as <%= and %> – This is a very bad idea.
So why are these a bad idea? Well, remember that one of the goals of writing software is
that you want your code to be able to run in as many environments as possible with the
least amount of additional configuration required. Now, I know you’re lazy you want to
speed up your workflow and save a few keystrokes but here is the deal, you should
use <?php and ?> as your starting and ending tags for PHP because this gives you the
most amount of portability. The next two will work but you may need to edit the php.ini file
in order to do so. What if you write a plugin for WordPress and someone out in the wild
can not get it to run because you decided to use ASP Style Tags exclusively and their
hosting company does not allow ASP Style Tags? That’s not a situation you want to have.

PHP For Dynamic Websites


By using PHP, we can begin to make our websites dynamic. In fact you are viewing a
dynamic website on this very webpage. This is because most of the content you are
consuming right now is stored in a database, not in a static HTML file. By using PHP, we
can interact with a database and get dynamically generated content to serve based on
many criteria. Let’s walk before running though and start with some simple commands.

echo
Just above, we had already made use of the echo command in PHP. Using this command,
we can do exactly what it says, echo something to the screen. There is another way to do
this as well. In fact, almost anything you can do in programming, you’ll find that there are
many ways to do the same thing. For example, we could rewrite our prior example using
the print command just like this.
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to PHP</title>
</head>

<body>

<?php
print 'This text comes from PHP!';
?>

</body>
</html>

Whether we use the first example of echo or the second of print, they will both produce
exactly the same thing in the browser. In fact in both scenarios, if you choose View Source
in your web browser, you can take a look at the HTML that was dynamically generated and
in both cases it looks just like this.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to PHP</title>
</head>

<body>

This text comes from PHP!


</body>
</html>

So that is great, and you may be wondering, “Well should I use echo or print?” What is the
difference between echo and print in PHP? There are a couple of differences to be aware
of.

1. echo is faster When PHP executes, the echo command will run faster than the print
statement. To be fair, you wouldn’t in a million years be able to tell the difference
because it is so minute, yet it is a fact that echo is faster.
2. print is a true function In PHP, the echo statement is not a language construct
however the print function is. This makes assigning a return value possible with the
print statement. This is a beginner tutorial however so we’ll just stick to using echo
unless we come across a need for print.

Studying The Request Response Cycle


A key ingredient to understanding how dynamic web pages work is to study the Request
Response Cycle. This encompasses the entire life cycle of requesting a webpage in your
browser from a remote server all the way to rendering it on the screen. How does this
process happen? Let’s imagine we are using the Google Chrome web browser and we are
requesting to view the index.php file on a remote linux server that is using the apache web
server software, PHP, and a MySQL Database. The process looks like this.
Chrome makes an HTTP request The first step is for the web browser to send an HTTP
request to the web server in question. This is simply a matter of loading something
like http://example.com/index.php in your browser.

• Apache finds the file This request is interpreted by Apache, and it looks in the
filesystem to find the index.php file.
• The file is interpreted by the PHP engine The web server knows that this file must
be run through the PHP Engine since it has a .php extension.
• The MySQL Database is queried If the file contains any logic to perform a database
interaction, it happens at this step.
• Output is sent to the Browser The data is returned from the database, all PHP is
parsed, and all data is then wrapped up into the final HTML output which gets sent
back to the client. Chrome renders this HTML in the browser and displays a web
page to the user.
The PHP Interpreter Does Not Care About Whitespace
Much like JavaScript, the PHP Engine does not care about whitespace. With JavaScript,
we always see developers minify their code before production. This strips out all
whitespace and non essential characters to produce one massive string of largely
unreadable JavaScript. The web browser doesn’t care however, it is able to run the
JavaScript just the same. With PHP, it is the same idea. There is no need for minification
on the server side however since the file size is not important. The PHP code itself will live
on the server and stay on the server as it executes, unlike JavaScript which must be sent
across the network before the Web Browser can do it’s thing.
This example function will run just fine when called upon.
<?php
function ssba_shorten($urlLong){$hmtlBitly=

file_get_contents('http://api.bit.ly/v3/shorten?login=ninja&apiKey=R_supersecretkey&longUrl='.$urlLon
g);
$arrBitly=json_decode($hmtlBitly,true);$urlShort=$arrBitly['data'];
$urlShort=$urlShort['url'];$hmtlBitly=str_replace('[]','',$hmtlBitly);if($urlShort!=''){return
$urlShort;
}else {return $urlLong;};}

However, you will make things infinitely easier on yourself if you use common formatting to
make the code readable.
<?php

function ssba_shorten($urlLong) {

// get results from bitly and return short url


$hmtlBitly =
file_get_contents('http://api.bit.ly/v3/shorten?login=ninja&apiKey=R_supersecretkey&longUrl=' .
$urlLong);
$arrBitly = json_decode($hmtlBitly, true);
$urlShort = $arrBitly['data'];
$urlShort = $urlShort['url'];
$hmtlBitly = str_replace('[]', '', $hmtlBitly);

if ($urlShort != '') {

return $urlShort;
} else {

return $urlLong;
};
}

If the above snippet doesn’t make a ton of sense to you, no need to worry. We’re only
using this to display the value of whitespace to the human coder, that would be you, and
the fact that the machine doesn’t care how the code is formatted – it simply reads in
source following the delimiters and control structures of the language as its means to
process it.

PHP Comments Syntax


We’ll now talk a little bit about comments in PHP and the syntax to use them. Comments
are so important, some would say even more important than the code itself. No matter
what language you happen to be programming in, using proper comments will save
yourself and other programmers that happen to be working on the project untold hours of
frustration while debugging. The funny thing is, is that when you are originally writing the
code and it comes time to include some comments, it is so easy to think, “This is so
obvious what is being done here, why would I ever need to add any comments?” If you
have ever found yourself thinking this, and then came back to this very same code six
months or a year later to hack in a modification, you’ll know how much it hurts to look at
that code and wonder what in this good green earths name were you thinking?! Now
consider that fact that you yourself are having a hard time figuring out what you did in this
earlier revision of the code. Now think about some other unlucky developer that has had to
take over your duties and codebase. If you’re having a hard time figuring things out here,
think of how this other dev must feel! These examples we’ll show here really don’t need
comments, but we’ll use these simple examples to just show how to use the syntax of
comments in your own php files.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to PHP</title>
</head>

<body>

<?php
echo 'Hi there Jimmy Bob.'; // First we say hi to Jimmy Bob using a one-line c++ style comment

/* We can just as easily note


that we are saying hi to
Jimmy Bob using a multi
line comment style like this */

echo 'Jimmy Crack Corn and I dont care';

echo 'Hey Jimmy, what is happening?'; # We can note that we are asking Jimmy what's going on
using a shell-style comment
?>

</body>
</html>
In the snippet above we make use of all three styles of comments you can use. You can
try all of them out and see which feels most natural. You can get really creative with these
and outline very specific comments at the beginning of various functions, classes,
methods, and so on. You’ll find that the popular PHP Frameworks have fantastic
comments.

• C++ Style Comments These are one line style comments using the double forward
slash notation //
• Multi Line Comments By using an opening /* and closing */ you can spread the
comment across several lines.
• Shell Style Comments Finally, you have the option of using shell style comments
with the hashtag # character.

The PHP Code Structure Summary


In this PHP Tutorial Series, we took a look at some key ingredients in getting yourself up to
speed with the overall structure of the PHP language. Can you do anything cool in PHP
yet? Well, probably not with just the info from this article. The key is however, though you
may want to jump into the most advanced php frameworks and do awesome things – if you
don’t know that basic structure of the code it uses, you won’t have a clue about what to do
when things don’t go right. There will be times when things don’t go right! So with that in
mind, we covered some real basic stuff here such as embedding php in a web page, using
proper start and end tags for your php code, making use of the right extension on php files,
using php for dynamic websites, learning about the request response lifecycle, whitespace
considerations, php code comments, and more. Now we’re ready to get busy and start
learning about how to make cool things happen in php in the coming posts.

PHP Variables and Strings Tutorial

Break out your Fender Stratocaster and put some fresh strings on. Plug in to an
epic Marshall Stack and crank it up to 11. Ask the crowd if they’re ready to rock
in your best British accent. We’re about to rock and roll with PHP Variables and
Strings. Our opening riff will tackle some of the naming conventions needed for
crafting your own variables and strings. Next up as you rip up and down the
fretboard, you’ll need to avoid some keywords that are not part of the scales of
your jam. Finally, you will rip into a solo and put your new found skills to use.
Let’s Rock and Roll.

PHP Variable Naming Conventions


Variables are a part of every programming language and PHP is no different. We use them
to hold information that is mutable, meaning we can insert, update, or remove values from
a variable. Think of a variable as a small chunk of memory in your computer. As their
name implies, variables will contain varying data over the course of their life cycle. PHP
variables follow a specific naming convention. Here are some of the guidelines to follow.
Begins With a $ Dollar Sign Every PHP variable will start with a dollar sign. Some people
love this while others find it irritating. It does serve a good purpose in the overall scheme of
things since when you are reviewing code, you can quickly identify anything that is a
variable. It does help with readability.

• Letter or Underscore The initial dollar sign needs to be followed by a letter or


underscore.
• Letters Numbers Dashes and Underscores The overall variable name can contain
any of these characters.
• No Spaces You are not allowed to have any spaces in the variable name.
• Case Sensitive Variables are case sensitive so $boo and $BOO are two different
variables.

PHP Variable Examples


<?php

$book = 'PHP Book';


$Book = 'JavaScript Book';
$soAwesome = 'Emmet';
$my_variable = 25;
$magazine4 = 'Sports Illustrated';
$_thing = 'rock';
$__coolThing = 'the ocean';

?>

The snippet above contains a bunch of valid variable names. If you were to use these in
your code, they would work just fine. There are some best practices involved however, so
let’s take a look at that idea. First off, the last example of $__coolThing is a bad idea. The
reason is that this variable begins with two underscores. While you can technically do this,
it can be very confusion to others who may need to work with your code. Making matters
worse is the $_thing style of creating a variable. PHP itself uses an underscore for special
use cases. You don’t want to be second guessing yourself when you come across these
instances with one or multiple underscores at the beginning. The overall best practice
variable style to use in PHP is in the form of $my_variable. This may be the case with other
languages, however in PHP you will find that many developers adhere to this style.

PHP Keywords
Another thing to keep in mind are the keywords that PHP already makes use of. These are
all language constructs. Technically, you could still use these as variable names, but why
would you do that? Don’t do it, since you’ll just confuse yourself and others.
__halt_compiler() abstract and array() as

break callable case catch class

clone const continue declare default

die() do echo else elseif

empty() enddeclare endfor endforeach endif

endswitch endwhile eval() exit() extends

final finally for foreach function

global goto if implements include

include_once instanceof insteadof interface isset()

list() namespace new or print

private protected public require require_once

return static switch throw trait

try unset() use var while


xor yield

Making use of PHP Variables


The easiest way to understand variables is to create a few of your own and start placing
data inside of them. Here, we’re going to create two variables and place varying
information into them, then echo them to the browser to confirm that the contents of said
variables are in fact updating and changing.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Variables in PHP</title>
</head>

<body>

<?php
$variable = 25;
echo $variable.'<br>';

$variable = 50;
echo $variable.'<br>';

$something_else = 'You sir, are awesome';


echo $something_else;
?>

</body>
</html>

On the first line we make use of the assignment operator = to place the value of 25into the
variable aptly named $variable. Line 2 has us using the echo language construct to output
the contents of $variable to the screen. On this same line, note that we use the
concatenation operator . to tack on an html line break tag so that we have some half
decent formatting in place when the script runs. At this point, when the script runs, the
browser will see the value of 25 on the screen.
As the script continues in a top down fashion like all PHP scripts do, we then take the
value of 50 and overwrite the existing value of 25. By simply re assigning a value to an
existing variable, we can overwrite or clobber as some programmers like to say, the value.
When we then echo the same variable to the screen, we can see it is now 50.Excellent work
Jedi.

On line 7 of the script, we create a second variable named $something_else. In the first
two scenarios, we placed number values into the variable. When we do that, we do not
need to enclose the data with single or double quotes. In this last example however, we
are trying to put a string into $something_else and this is why this data is surrounded by
single quotes. Single and double quotes have different meanings in PHP which we will get
to shortly. As the final step in this basic php program, we simply echo out the contents
of $something_else and confirm that yes – You sir, are awesome.
Raw HTML Output
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Variables in PHP</title>
</head>

<body>

25<br>50<br>You sir, are awesome

</body>
</html>

Rendered Browser Output


25
50
You sir, are awesome

Working With Strings in PHP


Strings are common in any programming language you might use. We’ve even used
strings already in this tutorial, so let’s look a little more closely at them. A string is merely a
collection of single characters. The characters can be letters, numbers, symbols, and so
on. This string of characters will be enclosed between either single or double quotes to
denote that you are actually dealing with a string. Now, it helps to keep in mind that when
working with strings, the double and single quote style of enclosing them has a different
meaning. You’ll still have a string, but the main difference is that with the double quotes,
PHP can make use of interpolation which means it can extract the value of a variable out
of that variable and display the value when the code runs. Single quotes do not allow this,
so when using single quotes you’ll find yourself making heavy use of the concatenation
operator is you want to make any strings of length with variables mixed in. Both
approaches work, try them out and see what you like best.

The Most Basic String Example


Starting right at the beginning, let’s look at a super basic string in PHP that we echo out to
the browser.
<?php
echo 'This is a really basic string in PHP. It\'s so easy even your Dog could do it';
?>

You might have noticed something there in the form of that backslash character . When we
use strings in PHP and the single quote style, if there are any single quotes within the
string, we’ll need to escape them so the PHP engine knows that this is not the end of our
string, it is an actual character we’d like to work with. This is easy to get tripped up on so
do make a note of it.

Putting HTML in a PHP String


We mentioned you can put letters, numbers, symbols, and so in into your strings. Well
guess what HTML is? That’s right, it’s a collection of characters and symbols used to
markup data in a webpage. This means, that’s right Nashville, that you can put real HTML
into your strings. With your imagination, you can create all kinds of wild and crazy things
using this approach. Let’s look at just a simple example.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Strings in PHP</title>
</head>

<body>

<?php
echo '<div class="alert alert-info"><h1>I Live in an H1 tag</h><br>';
echo '<h3>Isn\'t that pretty neat?</h3><br>';
echo '<span class="label label-success">Why yes, Yes it is good buddy.</span></div>';
?>

</body>
</html>

I Live in an H1 tag
Isn’t that pretty neat?
Why yes, Yes it is good buddy.

So we can see that by including HTML in the string itself, we can greatly change how the
browser displays the data.

Working With Double Quotes in PHP Strings


Now we’ll take that same snippet and change things up a bit. We’ll make use of some
variables, then place those variables in the strings to be sent to the browser. I know you’re
excited, so lets get right to it.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Strings in PHP</title>
</head>

<body>

<?php
$verb = 'am chilling';
$state = 'damn awesome';
$person = 'you excellent dude';

echo "<div class='alert alert-info'><h1>I $verb in an H1 tag</h><br>";


echo "<h3>Isn't that pretty $state?</h3><br>";
echo "<span class='label label-success'>Why yes, Yes it is $person.</span></div>";
?>

</body>
</html>

I am chilling in an H1 tag
Isn’t that pretty damn awesome?
Why yes, Yes it is you excellent dude.

Now this example highlights a few key points. Note that we changed our start and end
quotes in the echo statements to use double quotes. Do you notice anything else different
about those lines from the prior example? Yes that’s right, the double quotes that were
used for class definitions have been changed to single quotes as well as the single quotes
themselves no longer need to be escaped using a backslash. Also notice that in the
output, PHP happily extracted the values we had placed into our variables and output them
to the browser just like we thought they would using interpolation. You’ll also note that the
very first three variables we declared above were assigned strings. So it is quite easy to
assign a string to a variable, and you can make it as long as you like. A test is in order.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Strings in PHP</title>
</head>

<body>

<?php
$longstring = "This is a string. It's going to be a long one too. That is because we are testing
the practice of assigning strings to variables in PHP. So, let's include some random thoughts and
ideas to make this string have a good length. We could just as easily visit lorem ipsum dot com or
something like that, but who wants to read that crap? Let's instead talk about the Sun, the Moon,
the Ocean, and all other kinds of things while walking on the beach. Yeah.";

echo $longstring;

echo ' Pretty neat, that sentence is '.strlen($longstring).' characters long';


?>

</body>
</html>

So that was pretty slick. Note that we did make use of a string function there as well. We’ll
get to more details about string functions soon, but for now just now that this particular one
gives us the length of a string. So the full output of that test gives us:
This is a string. It’s going to be a long one too. That is because we are testing the practice of
assigning strings to variables in PHP. So, let’s include some random thoughts and ideas to make this
string have a good length. We could just as easily visit lorem ipsum dot com or something like that,
but who wants to read that crap? Let’s instead talk about the Sun, the Moon, the Ocean, and all other
kinds of things while walking on the beach. Yeah. Pretty neat, that sentence is 457 characters long
Very nice.

The Rocking Conclusion


You might not be a full fledged rock star just yet, but your PHP variables and strings skills
have hit at a minimum indie buzz status. Keep practicing, and soon enough, you’ll be filling
stadiums worldwide.

Introduction to PHP – Variables and Data


Types
We’ve covered a bunch of front end design and programming in some recent posts a la,
twitter bootstrap. What about minding the back end? When we talk back end, we talk PHP.
What is PHP? It’s a cool programming language efficient in many ways used to
communicate with a database, generate sessions and cookies, drum up unique content to
serve to a browser, and even interact with third party API’s or Application Programming
Interfaces.
PHP is a broad topic so we’ll break it up into many blog posts, but let’s start at the
beginning here and talk about variables and data types.

Data Types in PHP


PHP supports the following basic data types:
Integer—Used for whole numbers
Float (also called double)—Used for real numbers
String—Used for strings of characters
Boolean—Used for true or false values
Array—Used to store multiple data items
Object—Used for storing instances of classes
In addition to the above listed data types, PHP also has a NULL and resource type. If a
variable has not been assigned a value, has been explicitly set to NULL, or has become
unset, then it is said to have a NULL value. You may run into the resource type when
dealing with files and databases as the functions in PHP often make use of a resource
when you need to open a file for reading or connect to a database. What this means is that
they give you a file handle or database connection as a resource, which you can then use
to pass to other functions.

Type Strength
PHP is a weakly typed language which means that a variable does not need to be
declared with a type, you simply assign values to the variable regardless of data type.
Their are pros and cons to this approach. For the experienced programmer, it can save
time. For the newcomer, it may lead to some strange results.
Consider the following code:
<?php

$value1 = 1;
$value2 = 2.00;

$value1 holds an integer value, simply because the number 1 was assigned to it. $value2
on the other hand is a float since 2.00 is a floating point value.
Now get ready to have your mind blown.
<?php

$value2 = 'I can change the data type on the fly';

$value2 is now a string! By assigning the string value to the variable, you are allowing PHP
to update the variable type based on what has been assigned to the variable. We need to
cover MUCH more ground, but this is a super simple intro to PHP variables and data
types. See you in the next post!

What a Constant is and how to declare one

In PHP values that are stored in variables are updated all the time. What
happens when you need a value to maintain consistency though? For that you
can use constants. Similar to how we can assign a value to a variable, we also
assign a value to a constant but the difference is that once you set that constant
value, it cannot be modified. Let’s say you want to be sure the values of certain
variables will not change in your application. For example it would be smart to
determine that your variable named $oneminute has a value of 60 seconds. We
can declare that in a constant like so:
<?php

define( ‘ONEMINUTE’, 60);

Notice that we use the define keyword and the constant is in uppercase with no dollar sign
prefix. A different application might be setting the value of a T-shirt you might want to sell
on your website. Maybe you want to be sure it sells for $15 and will not be altered
elsewhere by the program. Let’s create that constant now:
<?php

define(‘TSHIRT’, 15);

Now you can be confident that when you are doing calculations and updates using the
TSHIRT constant, the correct value will be assigned to that constant. You can be confident
that the correct value is present and will not get modified by accident.
The uppercase convention of constants comes from the C programming language. C is the
foundation of all computer science and runs everything from the popular Linux operating
system which often runs apache and MySQL to serve up webpages, to the operating
system of cisco routers and switches, both of which power the vast majority of the internet.
Having this uppercase format makes it easy to identify in the code.
You are free to define as many constants as you may need in your program. PHP has a
large amount of its own pre-defined constants. To check which are in use on your
particular installation, you can run the phpinfo() function in one of your pages to view a
dump of all the configuration parameters including constants.
Be sure to also note that constants can only store values of type integer, float, Boolean, or
string. In other words, constants are used for scalar data type storage.

Understanding PHP Variable Scope


In PHP as in other programming languages, scope identifies areas in a program or script
where a given variable is visible. There are many scope rules and here are the most
important ones.

• The native super globals can be viewed anywhere in the program.


• Constants can be used outside as well as inside functions, i.e., they have global
visibility.
• When you define a global variable in a script, that variable will have visibility in all
areas of that script except for inside of functions within that same script.
• Variables that get declared inside of functions as global will refer to the global
variables that share the same name.
• Static variables declared inside of functions can’t be seen outside of the function, but
they do retain their value between function calls.
• Plain vanilla variables inside of functions will be destroyed and unusable once the
function has completed its execution.
• The arrays $_GET and $_POST have special scope rules. They are the well known
superglobals with visibility everywhere outside and inside of functions.

The following is a list of superglobal variables. Memorizing these will help as we move on
do more in depth features of PHP.
<?php

$GLOBALS //An array of all global variables (Like the global keyword, this allows you to
// access global variables inside a function. for example, as $GLOBALS[‘somevariable’].)
$_SERVER //An array of server environment variables
$_GET //An array of variables passed to the script via the GET method
$_POST //An array of variables passed to the script via the POST method
$_COOKIE //An array of cookie variables
$_FILES //An array of variables related to file uploads
$_ENV //An array of environment variables
$_REQUEST //An array of all user input including the contents of input including
$_GET, $_POST, and $_COOKIE (but not including $_FILES since PHP 4.3.0)
$_SESSION //An array of session variables
When starting out with PHP, or even if you are more advanced, it is important to be aware
of these important aspects of the language. While mundane, having these concepts
mastered will allow you to really focus on the cool things you can do with the language
once we get to the nitty gritty.

PHP Booleans and Constants Tutorial

So far in this PHP Tutorial Series we have taken a good look at all of the
basics. Some of the topics we looked at include what PHP is is, and what the
history of PHP has been. Moving on from this we covered the beginnings of
variables and strings, two of the most common concepts you’ll run across when
programming in PHP. We then got funky with integers, floating point values,
arrays, and more. Do you see a pattern here? That’s right, we’re hammering
home the basic types so that when we get to more advanced topics, we won’t
even have to think about these things. They will just be second nature. This
leads us to today’s episode of working the Booleans and Constants. They’re
definitely not the most exciting thing in the world, but we’ll try to keep it fun, and
they are a vital component of programming so let’s review them now!

Booleans
Booleans are a really basic thing, they are a just like binary. This is to say you either have
a 1 or a zero, a true or a false value. Booleans can either be true or false, that’s it. If it is
true, this does not means the string true or the number 1, it is simply a truthy value. They
are really useful in programming since we can make use of them to perform various tests.
We’ll be making use of this technique all the time to decide which conditional branch to
take. Booleans can be a little finicky so we should look at a few examples.
<?php

$true = true;
$false = false;

echo $true.'<br>';
echo $false.'<br>';

echo is_bool($true).'<br>';
echo is_bool($false).'<br>';

var_dump($true).'<br>';
var_dump($false).'<br>';

?>

1
1

boolean true

boolean false

There are a few points to consider here. First up, notice that we assigned the boolean
values using lowercase. Some will say you should always use uppercase, however for
the lazy efficient among us, why create the need to hold down the shift or caps lock key if
the end result of true or false is the same? Now the next thing we do is to echo out
these boolean values to the screen. Do not be confused! When using the echo command
in PHP, the language will always try to convert whatever it is you are echoing into
a string. So when you echo out a true boolean, PHP decides that this should be
represented by 1. Ok, makes sense, right? Now, when PHP echoes out a false value, the
same type juggling takes place however instead of outputting a 0 like you think it might, it
simply outputs nothing. Strange Behavior indeed.
To be sure of what you are dealing with, you can make use of the is_bool() function to
check if the variable contains a boolean. You may also want to make use of
the var_dump() function since it outputs both the type and the value for you. Types are a
bit confusing, but the more you work with them, the easier they become to manage.

Constants
It’s nice to be able to make use of variables in programming to be able to do all kinds of
interesting things. There are times when it is needed that we need to store a value in a
variable and keep it that way. You can almost think of a constant that way. It is a technique
to assign a value to a non changing variable, and use it anywhere in the program. Maybe
variable isn’t the best name for this placeholder, and you know what, you’re right – that is
why we call them constants! Constants need to use ALL UPPERCASE and they must be
assigned a value using the define() function. You can not simply use the assignment =
operator like you can with variables. Let’s test it out.
<?php

define('TAX_RATE', 'Way too high.');

echo TAX_RATE;

define('TAX_RATE', 7.8);

echo TAX_RATE;

?>

Way too high.


( ! ) Notice: Constant TAX_RATE already defined in C:wampwwwphpconsoleindex.php(61) : eval()'d code
on line 5
Way too high.

So some strange things happened. First off, we defined the constant tax rate as a string
which is way too high. It echoed out to the browser just fine. Moving through the script
however, we realized that the actual tax rate would be a number value so we try to
redefine it. Guess what? You can’t do that! Once a constant is defined, it is set until the
end of the script life cycle.
Now there is a bit more to constants so let’s examine. Check this out.
<?php

echo __LINE__.'<br>';
echo __FILE__.'<br>';
echo __DIR__.'<br>';

?>

1
C:wampwwwphpconsoleindex.php(61) : eval()'d code
C:wampwwwphpconsole

We didn’t define anything to those constants, yet look at the data they
Now wait just a second!
output when we echo them to the browser! You are witnessing magic my friend, yes
magic. Actually, PHP has a bunch of predefined constants that you can make use in your
scripts right away. As we can see by the example here, __LINE__ provides the line
number which is currently executing. __FILE__ provides the path and filename of the
currently running script. __DIR__ gives us the directory where the currently executing file
lives. These are all very handy, and the fun doesn’t end there. There are also some more
advanced constants to make use of like __FUNCTCION__, __CLASS__, __TRAIT__,
__METHOD__, and __NAMESPACE__ but we’ll get to those in due time as they are a bit
more advanced. For now, as long as we understand the concept of what a constant is and
how we can use it, we’ll be good to go.
The Action Packed Boolean and Constants Summary
Like we mentioned at the outset, booleans and constants might not set the world on fire
with their operation, but they are key concepts to understand when programming.
Booleans are especially key since pretty soon we’ll start looking at conditional statements.
It is by looking at a boolean value that we determine which actions should take place in our
code. Once we’re rocking and rolling with if statements, if else statements, if else if else
statements, switch statements, and so on, booleans will be the very thing that determines
how all of these things work. So while it is true that booleans seem boring with their on or
off true or false nature, we need to have them down cold before moving onward!

PHP Flow Control Statements

It’s time to get with the program friends – we need to Go With The Flow. In this
episode of our PHP Tutorial Series we’ll be taking a closer look at all of
the Flow Control Statements available to us. When we’re working with these
control statements, we’ll be evaluating variables and expressions for
a boolean value and then taking action based on a true or false state. Aren’t
you so glad we just covered booleans now?! In any event we have a lot to
cover, we’ll look at if, elseif, ternary, switch, while, for, foreach, try catch,
and return. Let’s jump into working with the various flow control statements we
have in PHP!
1. if
The workhorse of creating basic conditional logic in your programs is the
trusty ifstatement. We use the if statement to check the boolean value of a variable or
expression contained within a pair of parenthesis. The expression is checked, and if it is
true, the statement will run. No doubt you have seen this before, but let’s look at the
structure of this statement here.
if(expression) {
statement
}

Just as useful is the ability to specify some other statement to run should the expression
being evaluated be false. We can do that with this structure.
if(expression) {
statement
} else {
statement
}

There are opinions abound on the use of the curly braces. If you were to omit them, the
code would still run. There is a fair chance however that the code readability police will
hunt you down and place you under arrest for sloppy coding. The take away, use your
curly braces! If you really have a thing against the curly braces, you could use this
alternative syntax as well.
if(expression) :
statement
else :
statement
endif;

This approach sometimes works if there are large amounts of html in the file you happen to
be working with. You might see this type of syntax in a view file for instance in a model
view controller type application. You can also nest if statements to get the behavior you
want.
if (expression) {
statement
} else {
if (expression) {
statement
} else {
statement
}
}
You can use the above style all you like. If you want to use yet another syntax for the same
effect, you can do that as well. This would be by combining the else and if into one elseif.
This approach is not mandatory, in fact some would say the first approach is a bit more
readable. We’ll show how to use this additional syntax however for completeness.
if (expression) {
statement
} elseif (expression) {
statement
} else {
statement
}

As they say in Hollywood, whatever blows your hair back friend.

2. ? :
You may be wondering, whats up with the question mark colon in large font? This is the
ever useful ternary operator, and you can think of it as a shorthand expression of a simply
if statement. It’s a handy syntax that isn’t used as much as you’d think it would be. With the
ternary operator, the expression is first evaluated. Then, if that expression is true,
statement1 will run. If the expression is false, statement2 runs. The syntax is shorter, but
contrary to the if statement, it is sometimes not clear exactly what the intended effect was
meant to be when reading the code at a later time. This is the syntax if you would like to
use it.
(expression) ? statement1 : statement2

3. switch
Now we move on to the switch statement. When would we want to use the switch
statement? The switch statement is good when a variable could have one of several
values, and each value would have a different operation associated with it. A good
example might be a variable of $day. Consider there are seven days in the week, and
depending on the day of the week, your program would take a different action for each
scenario. This is how the syntax looks.
switch ($day) {
case 'Monday':
// wipe the cobwebs from your eyes
break;
case 'Tuesday':
// do productive stuff at work
break;
case 'Wednesday':
// cheer for hump day
break;
case 'Thursday':
// grab a beverage on thirsty Thursday
break;
case 'Friday':
// Celebrate the Weekend
break;
case: 'Saturday':
// Keep Celebrating
break;
case: 'Sunday':
// go to Church
default:
// Have a default action if the $day is something other than
// Monday - Sunday
break;
}

There might be a scenario where you want the same action to take place for several
different states of the variable being tested. Maybe you’d like to start celebrating the
weekend on Wednesday, Thursday, and Friday. You can do just that with a fall through
like this.
switch ($day) {
case 'Monday':
// wipe the cobwebs from your eyes
break;
case 'Tuesday':
// do productive stuff at work
break;
case 'Wednesday':
case 'Thursday':
case 'Friday':
// Celebrate the Weekend
break;
case: 'Saturday':
// Keep Celebrating
break;
case: 'Sunday':
// go to Church
default:
// Have a default action if the $day is something other than
// Monday - Sunday
break;
}

4. while
Moving on in our control flow adventures brings us to the while loop. This is the first loop
we have taken a look at. The format follows this format.
while(expression) {
statement
}

That looks an awful lot like an if statement you might be thinking. In fact you are right, the
only difference is that the if is now a while. The way this works is expression is evaluated
and if it is true, the statement runs. The expression then gets evaluated again, and if still
true, the statement runs again. This happens at lightning quick speed, and you can
complete hundreds of statement executions very quickly. The statement will usually have
an ability increment the expression so that the loop does not run forever. If it did not have
this ability, the loop might continue to infinity and the world would end program would
crash. Let’s count by tens to 100 with a while loop.
<?php

$i = 1;
while($i <= 10) {
echo ($i * 10);
echo '<br>';
$i++;
}

?>

10
20
30
40
50
60
70
80
90
100
One other thing you might like to do with your loops is to be
Easy Peasy Lemon Squeesy, People.
able to filter within them and break out of them if needed. You can do this by placing an if
inside the loop and a break inside the loop respectively. Let’s check each number to see if
it is evenly divisible by 3 and output a message indicating so if this is the case. Let’s also
break out of the loop at 80.
<?php

$i = 1;
while($i <= 10) {
$num = ($i * 10);

if(is_int($num / 3)) {

echo "$num is divisible by 3";

} else {

echo "$num is not divisible by 3";


}

echo '<br>';
$i++;

if($num == 80){
break;
}
}

?>

10 is not divisible by 3
20 is not divisible by 3
30 is divisible by 3
40 is not divisible by 3
50 is not divisible by 3
60 is divisible by 3
70 is not divisible by 3
80 is not divisible by 3
Smashing! That was awesome stuff.

5. do while
You could rewrite the prior example with a do while loop. The difference with a do while
loop is that since the while condition comes after the actual statement code, the loop will
always run at least a minimum of one time no matter what. With the standard while loop,
there is a chance that the loop will never run at all, since if the expression is false, the loop
won’t run! You’ll have to explore your use case, but it’s safe to say that do while loops are
far less common than while and the other types of loops. This is how to write one if you like
though.
<?php

$i = 1;
do {
$num = ($i * 10);

if(is_int($num / 3)) {

echo "$num is divisible by 3";

} else {

echo "$num is not divisible by 3";


}

echo '<br>';
$i++;

if($num == 80){
break;
}
} while($i <= 10);

?>

6. for
The for loop is really the workhorse of looping constructs. It’s a little more clean than the
while loop since it builds the counter right into the expression. No need to have an iterator
in the statement body of the loop with this scenario. We can rewrite our little counting
program with a for loop just like this. Note that the filtering and break mechanisms work
just as well in for loops as they did with while loops. In fact, let’s do the same program but
count by 100’s this time and break the loop at 700. Observe.
<?php

for($i = 1; $i <= 10; $i++) {

$num = ($i * 100);

if(is_int($num / 3)) {

echo "$num is divisible by 3";

} else {

echo "$num is not divisible by 3";


}

echo '<br>';

if($num == 700){
break;
}
}

?>

100 is not divisible by 3


200 is not divisible by 3
300 is divisible by 3
400 is not divisible by 3
500 is not divisible by 3
600 is divisible by 3
700 is not divisible by 3
Oh man, that is Cool and The Gang!

7. foreach
We talked a lot about arrays in this PHP Tutorial Series. We even came up with an
Epic PHP Array Functions List to keep as a reference. The time has come now, for us to
iterate over arrays. We will do this with the always useful foreach construct. Sometimes
you’ll just want the values, and other times you might like to get the keys and the values.
There are also a couple of ways to create the loop, so in total you have four options for the
syntax.
foreach ( $array as $value ) {
// do stuff to the value
}

foreach ( $array as $value ):


// do stuff to the value
endforeach;

foreach ( $array as $key => $value ) {


// do stuff to the key and value
}

foreach ( $array as $key => $value ):


// do stuff to the key and value
endforeach;

Now let’s put our foreach skills into action. Let’s say we have an array of stocks and we
want to process each one of them in turn. We’ll take an array of ticker symbols that are in
all lowercase. We’ll then place a function inside the loop of our foreach construct, and each
time the loop runs, and new lowercase ticker symbol will be fed into our strtoupper
function. We’ll simply echo this process out to the browser to see it in action.
<?php
$stocks = array('msft', 'goog', 'aapl', 'adbe', 'csco', 'jnpr', 'gpro', 'nflx');

foreach($stocks as $stock) {
echo strtoupper($stock).'<br>';
}

?>

MSFT
GOOG
AAPL
ADBE
CSCO
JNPR
GPRO
NFLX
Now we want to be able to process not only the ticker symbol, but the name of the
company each ticker symbol is associated with. We can do this using the key value pair
syntax of our foreach loop. Check it out.
<?php

$stocks = array(
'msft' => 'Microsoft',
'goog' => 'Google',
'aapl' => 'Apple',
'adbe' => 'Adobe',
'csco' => 'Cisco',
'jnpr' => 'Juniper',
'gpro' => 'Go Pro',
'nflx' => 'Netflix'
);

foreach ($stocks as $stock => $company) {


echo 'The stock ticker for ' . $company . ' is ' . strtoupper($stock) . '<br>';
}

?>

The stock ticker for Microsoft is MSFT


The stock ticker for Google is GOOG
The stock ticker for Apple is AAPL
The stock ticker for Adobe is ADBE
The stock ticker for Cisco is CSCO
The stock ticker for Juniper is JNPR
The stock ticker for Go Pro is GPRO
The stock ticker for Netflix is NFLX
So you can see that by using the foreach construct we can quickly get access to indices,
keys, and values in both standard index based arrays as well as associative arrays.

8. try catch
We all know that computers and the software that run them are 100% fail proof, error free,
and work perfectly at all times. If you believe that last sentence, there is a bridge in
Brooklyn you may consider buying Actually, the try catch construct is available to us
for the very fact that sometimes things can and will go wrong with our software. The try
catch gives us the ability to try something out, and if things don’t go as planned we have a
contingency plan to handle any problems. A perfect example is connecting to a database.
There are several things that could go wrong. To deal with this, just put your code in a try
catch block like so.
<?php

try {
$dbhandle = new PDO('mysql:host=localhost; dbname=vegibit', 'root', '');
if ($dbhandle) {
echo 'We are ready to work with the database!';
}

catch (PDOException $error) {


echo "Whoops! That was an error: " . $error->getMessage() . "<br/>";
die();
}

?>

We are ready to work with the database!


If something went wrong, like the database not being found, we get an error.
<?php

try {
$dbhandle = new PDO('mysql:host=localhost; dbname=verge', 'root', '');
if ($dbhandle) {
echo 'We are ready to work with the database!';
}

catch (PDOException $error) {


echo "Whoops! That was an error: " . $error->getMessage() . "<br/>";
die();
}
?>

Whoops! That was an error: SQLSTATE[HY000] [1049] Unknown database ‘verge’


Script ended unexpectedly.

9. return
The return statement is used so much we don’t even think of it many times. It just exists
happily in our code, returning values or control to the calling code going about it’s
business. Usually we’ll see return being used in a function something like this.
<?php

function add ($num1, $num2) {


return $num1 + $num2;
}

$result = add(5,7);

echo $result;

?>

12
In this code we create a user defined function that returns a value. You necan see when
we call that function by simply writing it’s name and passing in two variables, it assigns or
returns the sum into the variable $result. We are then free to echo out that value to the
screen. Pretty Slick!

Using Operators in PHP


Operators are the secret sauce to your PHP. In fact they are the secret sauce
to all programming because without them, you’d be doing a whole lot of nothing
with the data you are trying to manipulate or operate on!
Operators are used with arguments. They are the data being operated on, also called
Operands. One or many arguments can be used in these operations, though most
commonly you will see two arguments. For example 10 > 5 or $foo = $bar.
Arithmetic Operators
If you remember or know Algebra then arithmetic operators are going to be easy peasy for
you as they are just the normal mathematical operators.
Check em out:
OperatorName Example
+ Addition 1 $a + $b
– Subtraction 1 $a - $b
* Multiplication 1 $a * $b
/ Division 1 $a / $b
% Modulus 1 $a % $b
By using these operators in conjunction with the assignment operator, you can store
results like so:
$sum = $x + $y;
What this does is take the value of $x and $y then stores it in the variable $sum.
Subtraction would work in a similar fashion. Put calculations on the right of the = and store
the value to the left of the =.
You would read it as “$sum is set to $x + $y”.
One thing to note about the subtraction operator is that it can also be used to denote a
negative value stored in a variable like so:
$a = -1;
Multiplication and division
In programming you use the asterisk * for multiplication and the forward slash / for
division.
A special case arithmetic operator is the modulus which calculates the remainder of two
divided numbers. For example:
<?php

$a = 29;
$b = 10;
$result = $a%$b;

The value stored in the $result variable is the remainder when you divide 29 by 10 which
comes out to 9.
The arithmetic operators usually deal with integer and double data types. Due to the
loosely typed nature of the language, applying these operators to strings will cause
unexpected results as PHP starts automagically converting strings to numbers. Pay close
attention to your types in order to avoid creating bugs.
Operating on Strings
The concatenation operator or dot . is that magical glue that allows you to stick strings
together. It’s really fun and I know you will love it. An example is in order:
<?php

$hip = “I ”;
$hop = “am ”;
$hooray = “awesome”;

$result = $hip.$hop.$hooray;

The result is “I am awesome” and yes ladies and gentlemen, you are awesome.
Assignment Operators
To equals or not to equals, that is the question. The handy dandy = sign does not mean
‘equals to’ rather it means ‘is set to’. In a sense you might start to read code from right to
left. When you see
<?php

$myvalue = ‘cool text’;

You could read it in a right to left fashion as in, “cool text is assigned to $myvalue” or left to
right such as “$myvalue is set to cool text”. Whatever makes sense to you!
Values Returned from Assignment
The assignment operator returns a value just like other operators. For example:
$one + $two
Is an expression that results in the value of adding $one and $two.
Another example might be:
$ten = 10;
The value of this whole expression is integer ten.
Using this technique, you can create more involved expressions like:
$foo = 16 + ($bar = 5);
This line sets the value of the $foo variable to 21. First we evaluate the code between the
parentheses setting 5 to $bar, then adding 16 to 5, and finally assigning that entire value to
$foo. As you can see the parentheses work the same way as they do in math, which is to
give precedence to the sub expression between the parentheses.
Combination Operators
Many times in programming you will need to add a value to a variable such as
$x = $x + 10;
Rather than write it out in long form, you can use a combination operator like
$x += 10;
Combined assignment operators exist for all of the arithmetic operators and for the
string concatenation operator.
Pre and Post Increment and Decrement
Pre and post increment (++) and decrement (–) operators share traits with the +=
and -= operators, with some important differences.
Increment operators do two things, which is to increment and assign a value.
<?php

$hi = 7;
echo ++$hi;

On line two, the pre-increment operator is invoked. Interestingly, $hi will get 1 added to it’s
value and then echoed out to the screen as 8. Had the ++ come after the variable, it would
be printed to the screen as 7, and then it’s value would be incremented in memory.
The Reference Operator
The reference operator is represented by an &. What this does is to make reference to the
memory address of a variable rather than make a copy of the value itself. Typically what
happens when you create a variable and then assign that variable to a different one, a
copy gets created.
So setting $x = 7, $y = $x , and $x = 15 would leave you with 7 stored in $y and 15 stored
in $x.
Conversely if you did $x = 7, $y = &$x , and $x = 15 both $x and $y would have value 15.
This happens because $x and $y now point to the same memory address. To change this
relationship, you can use the unset() function.
Comparison Operators
When you need to check the logical value of an expression to true or false, you would use
one of the many comparison operators.
The Equal Operator
It’s easy to get the = and the == operators mixed up. The first refers to assignment, the
second refers to equality. Using == allows you to check if two values are equal to one
another. True is returned if they are equal and false is returned if they are not. Typically
non zero values are true and zero values are false.
Consider:
<?php

$five = 5;
$two = 2;

$five = $two;

$five = $two now evaluates to true! This is because the value 2 gets assigned to $five,
and 2 is a non zero value.
On the other hand:
$five == $two will now evaluate to false. Pay attention to your operators!
Other Comparison Operators
There are many other comparison operators that you will need to be aware of, they are
summarized here:
== Equals $c == $f
===Identical $c === $f
!= Not equal $c != $f
!== Not identical $c !== $f
<> Not equal (comparison operator) $c <> $f
< Less than $c < $f
> Greater than (comparison operator)$c > $f
<= Less than or equal to $c <= $f
>= Greater than or equal to $c >= $f
Logical Operators
Logical operators are important to test conditions. You can use AND, OR, XOR, and NOT
for this purpose. These are often used for checking conditions in control flow structures
and loops.
! NOT !$f Returns true if $f is false and vice versa
&&AND$c && $f Returns true if both $c and $f are true; otherwise false
|| OR $c || $f Returns true if either $c or $f or both are true; otherwise false
and AND$c and $f Same as &&, but with lower precedence
or OR $c or $f Same as ||, but with lower precedence
xor XOR $c x or $f Returns true if either $c or $f is true, and false if they are both true or both false.
Bitwise Operators
By using bitwise operators on integers, you will be able to deal with the exact bits that
represent the integer in question. Bitwise operators are more often used in a low level
fashion such as OS or Network programming in C. They are still available to you in PHP
however and we have them listed here:
& Bitwise AND$c & $f Bits set in $c and $f are set in the result.
| Bitwise OR $c | $f Bits set in $c or $f are set in the result.
~ Bitwise NOT ~$c Bits set in $c are not set in the result and vice versa.
^ Bitwise XOR $c ^ $f Bits set in $c or $f but not in both are set in the result.
<<Left shift $c << $f Shifts $c left $f bits.
>>Right shift $c >> $f Shifts $c right $f bits.
But Wait There’s More! (Operators)
Let’s cover the remaining operators you’ll run into now. The comma operator , is an
important one as it is used to separate arguments in functions and items in an array.
You will also want to be aware of the new and -> operators in order to create a new object
and access methods and properties within said object.
Kind of a control structure but formally listed as an operator is the ternary operator.?: This
handy dandy little bugger is great for having a shorthand form of an if elsestatement.
The form the ternary operator follows is:
condition ? value if true : value if false
Error Suppression Operator
PHP has many useful errors but sometimes you may not want to see them. In this case
you can use the @ operator to suppress them like so:
$error = @(200/0)
Normally this code would through a nasty warning, but we have suppressed it here with @.
Array Operators
Arrays are great fun and very useful. As such, we have numerous operators to use on our
arrays to make them easy to work with.
+ Union $c + $f Returns an array containing everything in $c and $f
== Equality $c == $f Returns true if $c and $f have the same key and pairs
===Identity $c === $fReturns true if $c and $f have the same key and value pairs the same order
!= Inequality $c != $f Returns true if $c and $f are not equal
<> Inequality $c <> $f Returns true if $c and $f are not equal
!== Non Identity$c !== $f Returns true if $c and $f are not identical
Type Operator
In object oriented programming we will cover the instanceof operator. It is used to check if
an object is an instance of a certain class. You would use it like so:
<?php

class awesomeClass{};
$obj = new awesomeClass();
if ($obj instanceof awesomeClass)
echo “obj is an instance of awesomeClass”;
If you made it this far, nice work! You now have the skills to operate successfully on your
data in PHP.

PHP Integers and Floating Point Values

We’ve covered a ton of information about strings in PHP and their associated
string functions, now we’ll take a look at working with numbers in PHP.
Numbers are important. If you think about it, we deal with numbers and math all
day, every day. It helps to be good with numbers for calculating your budget,
picking statistical favorites in your office fantasy league football team, investing
based on numerical data, and oodles of other scenarios. In PHP just like all
other programming languages we’ll typically be dealing with whole numbers
and decimal based numbers. In programming parlance we’d be referring to
integers and floating point numbers respectively. It’s a fairly straightforward
topic and can be fun as well, so let’s jump right in to integers and floating point
numbers in PHP!

Integers in PHP
When we think of integers, we’re talking about whole numbers. 1, 2, 3, 4, 5 and so on.
Integers can also have negative values, so going in the reverse direction is also valid. -1, -
2, -3, and so on are all integers as well. We can do simple math with integers and
everything works just like it does in Algebra. All of the orders of operation and operator
precedence hold true. Parenthesis can be used to assign priority to orders of operation.
Check out this example:
<?php
$variable1 = 9;
$variable2 = 4;
echo ((5 + 4 + $variable1) * $variable2) / 4 -3;
?>

15
As we can see, by following the standard math rules we come up with the answer of 15.

PHP Math Functions


PHP has several math functions that are quite useful, let’s have a look at a few of them.
<?php
echo 'Random Min Max - '. rand(1, 50).'<br>';
echo 'Random - '. rand().'<br>';
echo 'Modulo - '. fmod(30, 8).'<br>';
echo 'Square Root - '. sqrt(75).'<br>';
echo 'Exponential - '. pow(2,8).'<br>';
echo 'Absolute Value - '. abs(0 - 250).'<br>';
?>

Random Min Max – 7


Random – 9524
Modulo – 6
Square Root – 8.6602540378444
Exponential – 256
Absolute Value – 250
These functions work just like we would expect according to the standard math rules.
Going through the examples, first up is the Random number generation with a minimum
and maximum values. Here we provide a minimum of 1 and a maximum of 50. Each time
you run this snippet, you’ll get a random whole number between 1 and 50. You can also
run this particular function without providing a min or max value. The modulo takes two
numbers and divides them. It returns the remainder of that calculation. The square root
function calculates the square root of the number you provide to it. Exponential takes two
numbers, the number, and the exponent to assign the power of. Lastly in this group of
examples is the absolute value. This gives back the absolute value of the expression
within it. For example, if the result comes out to a negative value, the absolute value will
give you the actual value without the negative.

Increment and Decrement Numbers in PHP


When working in programming, we often need to add to or remove values from a variable
during the course of a script executing. There are a few ways to do this. First we’ll look at
incrementing a number.
Increment
<?php

$number = 5;
echo $number = $number + 5;

echo '<br>';

$number = 5;
echo $number += 5;

?>

10
10
These two examples do the same thing, however you can see their syntax is slightly
different. The first example takes the number, then it says assign this number plus 5 and
provide this to us. In the second example we use the plus equals shorthand notation. Note
that it works the same exact way and gives us the same result, but it is easier and faster to
type. This works just the same with multiplication, subtraction, and division. Don’t believe
it?! Check it out:
<?php

$number = 5;
echo $number = $number - 5;

echo '<br>';

$number = 5;
echo $number -= 5;

echo '<br>';

$number = 5;
echo $number = $number * 5;

echo '<br>';

$number = 5;
echo $number *= 5;

echo '<br>';

$number = 5;
echo $number = $number / 5;

echo '<br>';

$number = 5;
echo $number /= 5;

?>

0
0
25
25
1
1
Very Cool!

With the approach we were using above, we were dealing with incrementing and
decrementing by using the number 5. We can do this with any value that the problem to
solve may call for. A very common use case however is simply adding or subtracting one
to a number. This is so because when you work with loops in PHP, adding or subtracting 1
to the iterator happens all the time. Let’s see how to do this.
Post Increment or Decrement
This is the most common way to deal with adding or subtracting a value. Have a look at
this:
<?php

$number = 7;
echo $number++;

echo '<br>';

$number = 7;
echo $number--;

?>

7
7
Hey Wait! Those numbers are the same as when we started! This is because we are doing
post increment and decrement. You see what happens here is PHP echos out the value
first, then increments the variable. If we change up the code just a little, we can see how
this works.
<?php

$number = 7;
$result = $number++;
echo $number;

echo '<br>';
$number = 7;
$result = $number--;
echo $number;

?>

8
6
That’s more like it. In this snippet we make use of a second variable, $result. So the flow
looks like, assign 7 to $number, assign $number to $result then increment $number, echo
out $number. It’s a little tricky but will become second nature to you after a while.
Pre Increment or Decrement
You’ll notice that in making use of the Pre Increment or Decrement, the ++ or -
- goes before the variable, not after. It’s a subtle yet important difference. You can see that
when we echo out the value of the variable, the updated value is produced straight away.
How is this? Well in this case, PHP assigns 7 to $number, it then increments $number by
one, and finally produces the value to the screen. The same flow happens with the
decrement, and this is why the output is 8 and 6.
<?php

$number = 7;
echo ++$number;

echo '<br>';

$number = 7;
echo --$number;

?>

8
6

Strings Are Not Numbers


Strings are not numbers and numbers are not strings. Well this would seem painfully
obvious, yet it is easy to get tripped up with PHP since it does type conversion on the fly.
Consider this snippet:
<?php

$num1 = 1;
$num2 = '1';

if ($num1 !== $num2) {


echo 'not equal<br>';
}
echo $num1 + $num2;

?>

not equal
2
Verrrrry Interesting… In the first if statement we say if the first variable is not equal to the
second variable, then echo out not equal. This is exactly what happens when the code
runs. Note however that we then echo out variable 1, an integer, plus variable two, a
string, and we get the number 2. This should seem very strange to you if you’re new to
programming. The number 1 plus the letter one can not possibly be 2! What happens with
this is that PHP inspects the second variable and does its best to assume what is meant
by the string 1 in terms of a numerical value since we are trying to complete a math
operation. This is interesting how this type juggling works but you should really make sure
you know what types you are dealing with and explicitly set and convert them as needed
when programming. Don’t rely on PHP to do it for you lest you find yourself in a world of
hurt when you can figure out why things are not working.

Floating Point Numbers in PHP


This brings us to another type of number in PHP, the floating point. So what does this
mean? Do these numbers magically float among the clouds? Are they like a balloon filled
with helium? No, no they don’t do anything fun like that. Floating point is just a fancy way
of saying a number that has decimal places. We use floating points everyday in our lives.
Want to buy a coffee? Sure, that’ll be 2.47 please. There you go, you just made a floating
point transaction with your friendly Barista. See that, easy as pie.
Why Floating Point?
It may seem odd that with computers we need to have two types of numbers. In the real
world, we simply have numbers, and we deal with them accordingly. It turns out computers
compute and store numbers differently. Computers store integers and floating points in
different ways. Here are a few examples of some floats:
<?php

echo $float = 7.12;


echo '<br>';
echo $float + 5;
echo '<br>';
echo 5/3;

?>
7.12
12.12
1.6666666666667
You see we can assign a float to a variable, add a number to a float, or divide a number
which returns a floating point value.

Floating Point Functions


Sometimes it will be useful to apply any of the built in PHP functions for floats. We have
functions like round, ceil, and floor to do just that. Mainly, these are just simple rounding
functions and they do what their name appears as. This snippet gives you an example of
how these work:
<?php

$float = 7.12;
echo round($float, 1);
echo '<br>';
echo ceil($float);
echo '<br>';
echo floor($float);

?>

7.1
8
7
Is that a Float in your Pocket?
Is that a float in your pocket or are you just happy to see me? Many times you’ll need to
check a variable to see if it is a float or an integer. You might also need to simply check to
see if it is a numeric value. There are a few easy ways to do this, let’s see how.
<?php

$float = 7.12;
$integer = 5;

echo "Is $integer an integer? ";


if (is_int($integer)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}

echo "Is $float an integer? ";


if (is_int($float)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}

echo "Is $integer a float? ";


if (is_int($float)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}

echo "Is $float a float? ";


if (is_float($float)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}

echo "Is $integer a number? ";


if (is_numeric($float)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}
echo "Is $float a number? ";
if (is_numeric($float)) {
echo 'Yep!'. '<br>';
} else {
echo 'Nope!'. '<br>';
}

?>

Is 5 an integer? Yep!
Is 7.12 an integer? Nope!
Is 5 a float? Nope!
Is 7.12 a float? Yep!
Is 5 a number? Yep!
Is 7.12 a number? Yep!
The 11 Fun Hacks to Get Your PHP Integers and Floating Point Values Mastered Summary
We covered the beginnings of Integers, Floating Points, and Numeric Values in this action
packed episode of learning PHP fundamentals. So far we’ve take a look at the history of
PHP, how to work with strings, we covered PHP string functions soup to nuts, and now
we’ve got your numbers covered. Stay tuned for even more random bits of awesomeness
about PHP to come in the following episodes.

PHP URL Encode Example


We’ve covered a lot of technical detail concerning dealing with hyperlinks in
HTML here at VegiBit. As we have seen, when working with PHP, it is going to
be common and necessary that we process data and
information using variables. In this PHP Tutorial Series, we’re going to take a
look at how to generate links using PHP so that we can include variable data
via URLs and Super Globals. Specifically, we’ll need to learn what
a $_GET variable is, and how it works in combination with URL parameters.
Some other key points will be to learn what the reserved characters in URLs
are, what characters are unsafe, and when and how we’ll need to encode them
for proper use. The concepts here are in use all over the internet on virtually
every website you’ll ever visit. Let’s jump right in to working with URLs, Links,
and PHP.

1. The GET Super Global


When we’re working with URL’s and Links in PHP, we can pass variables via the URL
itself in the form of a query string. The query string is the part of the URL that comes after
the domain. The classic example of how to explain the way the GET Super Global and
html links work together is by creating two html pages and creating links between them to
show how the data is passed. We’ll set up two pages now. One with a link to page two,
and the other with some logic to dump the contents of the GET Super Global Variable to
the screen. Let’s check it out.
Page One
<html>
<head>
<meta charset="utf-8">
<title>Working With GET and Links in PHP Page One</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>
<?php
$make = 'Subaru';
$model = 'WRX';
$year = 2016;

echo "<a href='http://localhost/bootstrapsandbox/pagetwo.php?make=$make&model=$model&year=$year'>A


Car</a>"
?>
</body>
</html>

Page Two
<html>
<head>
<meta charset="utf-8">
<title>Working With GET and Links in PHP</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>
<pre>
<?php
print_r($_GET);
?>

Array
(
[make] => Subaru
[model] => WRX
[year] => 2016
)

By passing in values to the variables in the query string, we are able to pass data
Cool!
from one page to another via the GET Super Global variable.
2. Encode Your GET Values!
In HTML there are some reserved characters that we must be aware of because if we
include them in a query string without the proper encoding, the URL will break. This table
contains the reserved html characters we need to be aware of.
Reserved Characters in URLs

Char URL Encode

$ %24

& %26

+ %2b

, %2c

/ %2f

: %3a

; %3b

= %3d

? %3f

@ %40

Unsafe Characters in URLs

space %20

“ %22

< %3c
> %3e

# %23

% %25

{ %7b

} %7d

| %7c

%5c

^ %5e

~ %7e

[ %5b

] %5d

` %60

So as you can see, there are quite a few characters that could cause problems for you.
The solution is that instead of using the actual character in the URL, you should use the
the equivalent percent sign hexadecimal digits encoding value in the URL. Ok, we know
there are quite a few characters to be aware of, so go ahead and memorize the table
above, then come back once you’re ready to continue working with URLs in PHP.
You do not have to memorize this table, there are much better things to do with
Just Kidding!
your time! In fact let’s start making good use of that time by talking about the built in
functions in PHP that will do this for you. Don’t memorize all the characters, just remember
the functions to deal with them.

3. urlencode($string)
This here handy function is going to do the dirty work for you. By running the query string
through this function, it will convert any of the reserved characters to their percent / two
digit hexidecimal pair to make your life easier. Spaces become plus signs, while letters,
numbers, underscores, and dashes go through unchanged. We can see this in action and
why this is necessary by breaking our original link. Let’s add a variable to the list of
variables that we’d like to send via the query string. Here is the updated html.
<html>
<head>
<meta charset="utf-8">
<title>Working With GET and Links in PHP Page One</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>
<?php
$make = 'Subaru';
$model = 'WRX';
$year = 2016;
$mods = 'Stage Two Turbo & New Suspension';

echo "<a
href='http://localhost/bootstrapsandbox/pagetwo.php?make=$make&model=$model&year=$year&mods=$mods'>A
Car</a>";

$mods = urlencode($mods);
echo "<a
href='http://localhost/bootstrapsandbox/pagetwo.php?make=$make&model=$model&year=$year&mods=$mods'>A
Car</a>";
?>
</body>
</html>

So what we are doing here is adding a string to our $mods variable. The string is Stage Two
Turbo & New Suspension. Do you see a problem here? That’s right, we’re placing a
reserved character, the ampersand, in the string that we want to pass as a variable in the
URL. This is going to cause some unexpected results! To illustrate the problem, we
created two links, one with the $mods variable left untouched, and the other with
our $mods variable run through the urlencode function. Let’s see the difference.
Link 1
Array
(
[make] => Subaru
[model] => WRX
[year] => 2016
[mods] => Stage Two Turbo
[New_Suspension] =>
)

Link 2
Array
(
[make] => Subaru
[model] => WRX
[year] => 2016
[mods] => Stage Two Turbo & New Suspension
)

Do you see the difference? The first link completely breaks the data! It has turned the
contents of our $mods variable into two entirely different variables! This is sure to rain fire
from the heavens upon your web application. The second link however uses
the $mods variable after it has been massaged by the urlencode function and therefore
does not break our application. The string we wanted, Stage Two Turbo & New Suspension,
is safely nestled inside of the $mods variable with no ill effect. Excellent. Note that this
URL encoding is only needed with GET requests, since they use URLs to send data.
POST requests will not need any of this fancy encoding business.

4. rawurlencode($string)
In addition to the urlencode function, you also have this rawurlencode function available to
you when dealing with URL encoding. This function does all of the same things as
urlencode. Ok, so you may be wondering, why would you use rawurlencode instead of
urlencode. That’s a good question, and the answer will surprise you. (or not). The
rawurlencode converts space characters into %20 which is their percent / hexadecimal
encoding. Recall the urlencode just turns spaces into plus signs. So what’s the big deal
here? Well, there are some best practices to be aware of and here is a summary of when
to use each.

5. rawurlencode vs urlencode
rawurlencode the path

• the path is the part of the url that comes before the ? symbol
• spaces must be encoded as %20

urlencode the query string

• the query string is anything that comes after the ? symbol


• spaces are better encoded as plus signs here

Let’s take a look at this in action.


<html>
<head>
<meta charset="utf-8">
<title>Working With GET and Links in PHP Page One</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>
<?php
$make = 'Subaru Hatchback';
$model = '2016 WRX STI With Stage Two Turbo & New Suspension';

$linkone = rawurlencode($make)."?model=".urlencode($model);

$linktwo = urlencode($make)."?model=".rawurlencode($model);

echo '1st approach: rawurlencode ? urlencode<br>';


echo $linkone;
echo '<br><br>';
echo '2nd approach: urlencode ? rawurlencode<br>';
echo $linktwo;
?>
</body>
</html>

1st approach: rawurlencode ? urlencode


Subaru%20Hatchback?model=2016+WRX+STI+With+Stage+Two+Turbo+%26+New+Suspension

2nd approach: urlencode ? rawurlencode


Subaru+Hatchback?model=2016%20WRX%20STI%20With%20Stage%20Two%20Turbo%20%26%20New%20Suspension

There are two reasons you should use the first approach.
1. The portion that comes before the ? is where the server is going to be looking on the
filesystem for the file Subaru Hatchback. The server is going to have a better time looking
for a file that uses %20 as a space rather than a literal + sign. In fact the server may not find
this file at all if using a + sign, and your link will break altogether.
2. The portion that comes after the ? is going to be shorter and look much better
using + signs rather than %20. It’s true both methods will work in this case,
but urlencode after the ? is a best practice, so we should do it that way.

The PHP URL Takeaway


In this episode of our dive into the warm waters of programming with PHP on the web, we
took a closer look at dealing with special characters in the URL string. We need to do this
because these special characters have a specific meaning if they are part of the URL
string. In order for web browsers to interpret and render these URL Strings correctly, it is
key that we make proper use of encoding via urlencode and rawurlencode. Remember,
when dealing with query strings and URLs, it is best to follow a three step procedure. 1.
Find the ? question mark in the query string to divide the full URL into two parts. 2. On
the left hand side of the ?, use rawurlencode to encode the data. 3. On the right hand
side of the ?, use urlencode to encode the data. With this technique, you will navigate
your way around links, URLs, and PHP with ease.
PHP Include Vs Require

One goal that almost every software engineer on earth regardless of discipline
or language they subscribe to has a common goal in mind. This is to keep
things DRY. When we say DRY, we’re not talking about the Mojave Desert type
of DRY, we’re talking about Do Not Repeat Yourself. Hmmm, wait isn’t that
DNRY? Ok, let’s say Don’t Repeat Yourself. You get the idea. Whoops, there
was a repetition right there, see we all need to make an effort to keep it DRY! At
this point in the game, we have all manner of autoloaders, the wonderful
Composer Project, and countless frameworks that strive to help us organize
and maintain some type of sensible architecture that facilitates keeping your
code DRY. In this episode of the PHP Tutorial Adventure, we’ll take a look at
the Brilliant Functions the creators of PHP devised early on to help us with this
goal, and those would be the include, require, include_once, and require_once
functions. Yes, you likely have used these already, but it pays to dig in deeper
to make sure we understand the key points and differences of each approach.
Let’s jump in.

Keep It DRY
One of the great features of PHP is the ability to include code from other files into other
PHP files. Ok, big whoop, you’re probably thinking. You may be right, but this is an
important feature because it is by using this approach that the foundations of code
organization and reuse are born. Let’s keep it right down to basics at this juncture. Forget
frameworks, Composer, and any other advanced methods you might already be using.
We’re going back to procedural Function Based style right about now. Imagine you have a
page on your website and you just created a killer function that does some really awesome
processing of the data you’re working with. Now, two months later, in an entirely different
section of the website and codebase you have a need to process that data the very same
way your original killer function did. Are you going to write that function again? You might,
if you’re just starting, like all of us have done! A better way however would be to include or
require a file which contains the function code you would like access to. Maybe your
function is 30 lines long. In this new file, you can include the file on one line, then call it on
the next so to speak. 2 lines vs 32 lines is a nice ROI. Not only is the lack of typing a
motivating factor, but what if you find a bug in your super awesome function a few months
down the line. Say you had pasted that function code in ten different PHP files within your
website. Guess what Johnny, open up your favorite editor and get ready for some mind
numbing code maintenance because you are now going to have to fix that bug in 10
different places. You know what, Funk That. We’re going to make sure that doesn’t happen
again using the techniques here.

1. include($path)
There is one thing we didn’t mention yet about this fantastic function. This useful function
is not only for including PHP Code, you can place whatever you like in the file to be
included, such as HTML. Pretend your awesome page makes use of some common
elements in the head section, and you have 10 different pages that all use the same head
data. You don’t need to reinvent the wheel each time! Let’s see how this works.
yourawesomepage.php
<html>
<head>
<meta charset="utf-8">
<title>Keep It DRY and Win</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

Keeping It DRY Since A Long Time Ago. © ® ™

</body>
</html>

Now, rather than manually typing out all of that data in the head section into all of your
other pages, lets create a DRY Maker and include that instead.
the_dry_maker.php
<html>
<head>
<meta charset="utf-8">
<title>Keep It DRY and Win</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

Now, when you create your other awesome page, you can do so with style and grace just
like so.
<?php
include('the_dry_maker.php');
?>

<body>

Keeping It DRY Since A Long Time Ago. © ® ™

</body>
</html>

Notice that the Dry Maker file doesn’t even have any PHP in it. We are simply using PHP
in the includer file to include non PHP text from the includee file. What this means is that
when the include function runs, PHP essentially shuts off inside of it so you can import non
PHP data. This also brings up the point that if you want to include PHP from the other file,
you’ll need to make sure that you are turning PHP back on in that file. Let’s see this by way
of including an example function.

yourawesomepage.php
<html>
<head>
<meta charset="utf-8">
<title>Keep It DRY and Win</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

Keeping It DRY Since A Long Time Ago. © ® ™<br>

<?php
include('the_dry_maker.php');
echo highfive('Jim', 'Awesome');
?>
</body>
</html>

the_dry_maker.php
<html>
<head>
<meta charset="utf-8">
<title>Keep It DRY and Win</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<?php

function highfive($name,$state) {
$highfive = "You know what $name? You are $state, give me a high five!";
return $highfive;
}

?>

Keeping It DRY Since A Long Time Ago. © ® ™


You know what Jim? You are Awesome, give me a high five!
Nice! You can now include The Dry Maker file on any page of your website, and give a high
five to anyone you feel like, no need to write a new function every time. Now right now you
might just be giving a high five – but what happens once you start saving the world? Now
you can begin to see the power of the include function.

2. require($path)
When we look at require vs include, it might seem like they are basically the same. In fact,
PHP require and PHP include do all of the same things, except with the following
difference. If require can’t find the file you wish to load, PHP will raise a fatal error and
script will come to a screeching halt. In some cases this might make sense, but in others,
not so much. In the prior example, using include makes sense. It’s great to give high fives,
but probably not mission critical to our application. So if we fail to include The Dry Maker
file, the page will still try to finish executing. Now since we try to call a function on the page
which is referencing a function definition from another file which is now not included we’ll
get an error from that. The key point though is that the include itself will not cause a failure.
On the other hand, lets say your database driven site has all of its database functions in a
file like database_funcs.php. This is an important piece of code, so much so that your site
would not be able to run without it. In this case, require makes sense. Let’s see this in
action, we’ll change the code in yourawesomepage.php to have a typo for the file we’re
looking for. Then we’ll test out the require vs include and see what happens.
Require
<?php
require('tthe_dry_maker.php');
echo highfive('Jim', 'Awesome');
?>

• ( ! ) Warning: require(tthe_dry_maker.php): failed to open stream: No such file or


directory in C:wampwwwbootstrapsandboxyourawesomepage.php on line 16
• ( ! ) Fatal error: require(): Failed opening required ‘tthe_dry_maker.php’
(include_path=’.;C:phppear’) in
C:wampwwwbootstrapsandboxyourawesomepage.php on line 16

Include
<?php
include('tthe_dry_maker.php');
echo highfive('Jim', 'Awesome');
?>

• ( ! ) Warning: include(tthe_dry_maker.php): failed to open stream: No such file or


directory in C:wampwwwbootstrapsandboxyourawesomepage.php on line 16
• ( ! ) Warning: include(): Failed opening ‘tthe_dry_maker.php’ for inclusion
(include_path=’.;C:phppear’) in
C:wampwwwbootstrapsandboxyourawesomepage.php on line 16
• ( ! ) Fatal error: Call to undefined function highfive() in
C:wampwwwbootstrapsandboxyourawesomepage.php on line 17

See the difference?With the require, the script halts right in its tracks as soon as it can’t find
the file, and a fatal error is thrown. Conversely, the include only throws a warning when it
can’t find the file. Later on on in the page however when we try to call the highfive function,
a fatal error is thrown since you can’t call a function that is not defined.

3. include_once($path)
In order to show the difference between include and include_once, let’s modify
yourawesomepage.php to make multiple include calls to the same dry maker file we’ve
been working with to see what happens. Then we’ll try the same test with include_once
and discuss the results.
yourawesomepage.php
<html>
<head>
<meta charset="utf-8">
<title>Keep It DRY and Win</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

Keeping It DRY Since A Long Time Ago. © ® ™<br>

<?php
include('the_dry_maker.php');
echo highfive('Jim', 'Awesome');
?>

<br>

<?php
include('the_dry_maker.php');
echo highfive('Jim', 'Awesome');
?>

</body>
</html>

Page Output

• Keeping It DRY Since A Long Time Ago. © ® ™


• You know what Jim? You are Awesome, give me a high five!
• ( ! ) Fatal error: Cannot redeclare highfive() (previously declared in
C:wampwwwbootstrapsandboxthe_dry_maker.php:13) in
C:wampwwwbootstrapsandboxthe_dry_maker.php on line 16

What happens here is that the page runs just fine until it hits the second include statement.
At that point, include pulls in the file and PHP sees that highfive is getting declared again.
This is a big no no and a fatal error is thrown. Now let’s change the code to use
include_once.
yourawesomepage.php
<html>
<head>
<meta charset="utf-8">
<title>Keep It DRY and Win</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

Keeping It DRY Since A Long Time Ago. © ® ™<br>

<?php
include_once('the_dry_maker.php');
echo highfive('Jim', 'Awesome');
?>

<br>

<?php
include_once('the_dry_maker.php');
echo highfive('Jim', 'Awesome');
?>

</body>
</html>

Page Output

• Keeping It DRY Since A Long Time Ago. © ® ™


• You know what Jim? You are Awesome, give me a high five!
• You know what Jim? You are Awesome, give me a high five!

You see that when we use the include_once statement, we no longer get
Excellent, no errors!
the fatal error and the page runs perfectly. Why is that? This is because include_once
adds the original path to an array, and if it sees that path attempt to be included again it
will ignore it. So in this code above, when the second include_once statement is hit, PHP
now knows that the path provided was already included so it ignores it. This way, there is
never any attempt to redeclare the highfive function, and everything operates smoothly.

4. require_once($path)
Last up in our list of brilliant functions within PHP is the require_once function. This option
has the properties of the original require function, in addition to the fact that just like
include_once, multiple attempts to require the same file will be ignored. All 4 have specific
applications as you can see, so now you know which is best to use for your applications.

The Brilliant Takeaway


These are simple functions in PHP however they are incredibly powerful. What is
something that is simple, yet incredibly powerful? That’s right, it’s brilliant. We saw how we
can use the php include to include html by specifying the include path to the file in
question. This can be used for a header, or a footer, and it all works like magic on the
server side. By looking at php require vs php include, we also learned the differences of
how they may or may not throw a fatal error and when best to use them. The same can be
said for the php include_once vs php require_once.

Process HTTP Request With PHP

Everything we do with building websites has a dark underside, and it’s called
the HTTP Protocol. Actually, it’s not dark, it’s great as this is what makes all
this internet stuff possible. You see when you visit a website and the server
sends HTML to you over the internet, there is something that comes first,
before any of the HTML even gets to your browser. This is called the HTTP
Header and it contains some valuable information about the web session to
provide to the Browser. This gets sent before anything else. In fact, it is by the
very fact that you tried to visit a website in the first place that this process
began. When you go and type your favorite URL into your browser of choice
and then hit enter, what do you think happens? Your Browser makes use of the
HTTP protocol to send a GET request to the server in the form of an HTTP
Header. So you see all of this is the underpinning of how websites and the
internet works, so we’ll need to get a good grasp of how to use this in PHP.
There are tons of functions and approaches to working directly with HTTP and
HTTP Headers in PHP, so let’s get right into it!

Is HTTP Evil?
You may have noticed the scary implications that the title of this post assigns to PHP.
Actually, HTTP is not all that bad, it may be our friend in fact. It is a bit quirky and tricky at
first however, and this is why we must remain vigilant in our learning. One way to really
learn about the HTTP protocol is to install something like the Live HTTP Headers add on to
Firefox. This gives you the ability to watch all the communication between your web
browser and a remote server in real time. It is quite slick actually. If you have Live HTTP
Headers installed, you can click Tools->Live HTTP Headers and a new window will open
that displays all of the HTTP Headers in a web session. Here is an example of a Request /
Response to Twitter.
request
https://twitter.com/
GET / HTTP/1.1
Host: twitter.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101
Firefox/32.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: guest_id=example cookie data
Connection: keep-alive
response
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
Content-Encoding: gzip
Content-Length: 12361
content-security-policy-report-only: default-src https:; connect-src https:; font-src
https: data:; frame-src https: http://*.twimg.com http://itunes.apple.com about:
javascript:; frame-ancestors https:; img-src https: data:; media-src https:; object-src
https:; script-src ‘unsafe-inline’ ‘unsafe-eval’ about: https:; style-src ‘unsafe-inline’
https:; report-uri;
Content-Type: text/html;charset=utf-8
Date: Thu, 09 Oct 2014 14:36:46 UTC
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Last-Modified: Thu, 09 Oct 2014 14:36:46 GMT
ms: S
Pragma: no-cache
Server: tsa_a
Set-Cookie: _twitter_sess=example session cookie
status: 200 OK
The main thing to note here are the status codes. We can see that Twitter responds back
with a 200 OK, which is a way of saying, “Hey – Everything is Awesome”. There are a
whole range of status codes that exist to help facilitate communication between client and
server. Here is a table of them.

HTTP Code Number HTTP Code Meaning

Messages in the 100 range are informational

100 Continue

101 Switching Protocol

Messages in the 200 range indicate success

200 OK

201 Created

202 Accepted

203 Non-Authoritative Information

204 No Content

205 Reset Content

206 Partial Content

Messages in the 300 range deal with redirection

300 Multiple Choice

301 Moved Permanently

302 Found

303 See Other

304 Not Modified

305 Use Proxy


HTTP Code Number HTTP Code Meaning

306 unused

307 Temporary Redirect

308 Permanent Redirect

Messages in the 400 range indicate client errors

400 Bad Request

401 Unauthorized

402 Payment Required

403 Forbidden

404 Not Found

405 Method Not Allowed

406 Not Acceptable

407 Proxy Authentication Required

408 Request Timeout

409 Conflict

410 Gone

411 Length Required

412 Precondition Failed

413 Request Entity Too Large

414 Request-URI Too Long

415 Unsupported Media Type


HTTP Code Number HTTP Code Meaning

416 Requested Range Not Satisfiable

417 Expectation Failed

Messages in the 500 range are server errors

500 Internal Server Error

501 Not Implemented

502 Bad Gateway

503 Service Unavailable

504 Gateway Timeout

505 HTTP Version Not Supported

header($string)
Your web server takes care of sending the proper headers to your website visitors
depending on the situation. This is something we normally never even think about as it
happens automatically and transparently in the background. There are occasions when
you the developer may have a need to manually tweak how the headers are presented
from your server and in this case, you can make use of the header()function. Let’s look at
some code that would modify the headers.
<?php

header('Content-Type: application/pdf');

header('HTTP/1.1 500 Internal Server Error');

header('HTTP/1.1 404 Not Found');

header('Content-Disposition: attachment; filename="awesome.docx"')

?>
The code above gives examples of how you would send headers for an Adobe PDF
document, a Server Error, a not found page, and a downloadable attachment.

Headers Come First!


There is a really super important thing that you need to be aware of with regard to HTTP
Headers and that is that they come before all page data. They are first. The reason for this
is that the HTTP protocol is giving the users browser a heads up. It’s saying, “Hey, get
ready, there is some HTML Data about to be sent your way”. It may be telling it something
different, but the key point to know is that the HTTP Protocol enforces this, so we must be
aware of it. Any modifications you would like to do to the headers must be made before
anything else in your code. If the server begins to send anything, even one measly
whitespace character, you will encounter the oh so familiar Warning: Cannot modify
header information – headers already sent (output started at file:line).

Redirects In PHP
It is actually not all that common to be tinkering with headers in PHP, but there is a use
case that is used all the time and has real value. That use case would be Page
Redirection. Page Redirection is wonderful for instances such as when a user logs into
your site, maybe you’d like them to be redirected right to a key piece of information on a
given page. You can do that with Page Redirection. The popular PHP frameworks all have
this functionality in some easy to use methods, but we can do this right in native PHP as
well. Let’s see how.

302 Redirect
In the HTTP protocol we use a 302 Redirect to make a Page Redirect happen. There are
two parts to this.

• HTTP 1.1/ 302 Found


• Location: path

The first part says, “Hey you found me” and the second part says, “but you need to go to
this different location now”. Now when we do this in PHP it would look something like this.
Let’s say we’re redirecting someone to the login page.
<?php
header('Location: login.php');

You may be wondering why we didn’t have to manually set the 302 portion of the redirect.
This is because PHP is intelligent enough to do that automatically for you, so all you need
to do is provide the location to redirect to, and bingo. Pay attention to the syntax when
using this approach as it is notoriously finicky. The L in Location must be capitalized,
followed by all lowercase. The double colon must be followed by exactly one whitespace
character. Then you can provide the path to redirect to. What’s interesting is that the
browser actually immediately makes a second GET request once it sees that 302 Redirect.
One other point to keep in mind is that once the redirect happens in PHP, you really don’t
want to send any other data so often you’ll see an exit statement right after the command.
<?php
header('Location: login.php');
exit;
?>

You could even put this in a dedicated redirect function if you like. This is what it might look
like.
<?php
function redirect($new_page) {
header('Location: ' . $new_page);
exit;
}
?>

Now if you want to redirect somebody to Yahoo, you can just do this and send them on
their way.
<?php
function redirect($new_page) {
header('Location: ' . $new_page);
exit;
}

redirect('http://yahoo.com');
?>

The HTTP Header Redirect Conclusion


In this episode of our PHP Tutorial Series we learned all about the HTTP Protocol and how
it works with PHP. It may have started out scary, but now that we understand how it works,
it’s not so scary after all. The takeaways are that HTTP Headers always come first in web
based communications and each message has a status code associated with it. Our handy
table of status codes gives us an idea of which ones are informational, success, redirects,
client errors, or server errors. It will come in handy to at least know the basic associations
of the 100s, 200s, 300s, 400s, and 500s.

Process HTML Forms With PHP


Working with Forms when building websites seems so easy. There are in fact
many details to be aware of. In the HTML Tutorial Series, we had a good look
at an HTML Form Tutorial, but we didn’t get a chance to investigate how we
would actually process the data we collect from the form. Now we are in the
midst of a great PHP Tutorial Series and what better time to have a look at
Form Processing with PHP than right now. We learned that links and URLs
pass data via the GET super global. In this episode, we’ll take a look at the
POST super global, and how it ties in to processing forms in PHP. Let’s jump
right in!

3 Ways To Get User Data


• Links and URLs By making use of a query string, key / value pairs of data can be
passed via the GET super global
• Forms With HTML Forms, POST is the usual method of data transfer and does not
require encoding / decoding the way Links and URLs do
• Cookies By setting cookie values via PHP, you can then read and write data to an
associative array as needed

In this adventure we’ll be specifically targeting the 2nd approach with POST requests and
HTML Forms in PHP. It is by the $_POST super global variable that we can access data
submitted by the form. The various fields in the HTML Form will have a name attribute
which will then become the key of the associative array in $_POST. You can make use of
form processing via a 2 page process, or a single page form process. There are pros and
cons to each, and for now we’ll take a look at the 2 page approach. What this means is
that your first page will contain the HTML markup for the form. That form will have
an action attribute, and the value of that attribute is the second PHP page that will process
the data. The easiest way to see how this works is to create it in code.
htmlformbuiltwithlove.php
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Built With Love</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

<form action="process_form.php" method="post">


Website: <input type="text" name="website" value="" /><br>
Category: <input type="text" name="category" value="" /><br><br>

<input type="submit" name="submit" value="Submit Website" />


</form>

</body>
</html>

process_form.php
<pre>
<?php
print_r($_POST);
?>

So there we have our two page setup for form processing at its most very basic. If we load
up htmlformbuiltwithlove.php in our browser, we can enter some information into the form.
In the first field we will enter https://ello.co and in the second we’ll enter Social. Then
we’ll hit the Submit Button and see what happens.
Array
(
[website] => https://ello.co
[category] => Social
[submit] => Submit Website
)

Very Cool! You can see how the name attribute became the key in our array, and the data
we typed became the value of that particular key. This data was passed from page one to
page to via the POST method. Let’s look at grabbing the data out of that array and actually
using it. In your actual programs, the sky is the limit in terms of how you can process this
information. Let’s just grab the two values, put them in variables, then use them on the
page somehow. We’ll update the process_form.php file like so and see what we can do.
process_form.php
<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

<?php
$website = $_POST['website'];
$category = $_POST['category'];

echo "Hi bud, thanks for submitting <b>$website</b> to the <b>$category</b> category.";
?>

Hi bud, thanks for submitting https://ello.co to the Social category.

Detecting Form Submission


Now that we have an understanding of how to create a basic HTML form on one page, and
a PHP processing script on another, let’s now look at how to detect if there was a form
submission. This is a common and necessary step with processing forms in PHP. There
are many reasons for this, but one of the main ones is if a user tries to load the form
processing page directly, as this will cause errors in your application. So what’s the best
way to do this? Let’s have a look.

Set Default Values


One thing we can do is set up some logic to assign default values if needed. This way if
the user submits the actual form processing page instead of the HTML form itself, we can
set values to something sensible as needed. Using the ternary operator is an easy way to
do this.
process_form.php
<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

<?php

$website = isset($_POST['website']) ? ($_POST['website']) : 'http://twitter.com' ;


$category = isset($_POST['category']) ? ($_POST['category']) : 'Social' ;

echo "Hi bud, thanks for submitting <b>$website</b> to the <b>$category</b> category.";
?>

Loading the this page directly will provide “Hi bud, thanks for submitting http://twitter.com
to the Social category.”, however loading if you submit a blank form from
htmlformbuiltwithlove.php, the processing page will still run but it will have empty values.

A Better Form Detection Method


The prior example is a start, but there is an easier and better way. Let’s revise the form
processing script to have the following format.
process_form.php
<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

<?php

if(isset($_POST['submit'])) {
echo 'Nice Form Submission!<br>';
} else {
echo 'Stop trying to hack the form fool!';
exit;
}

$website = isset($_POST['website']) ? ($_POST['website']) : 'http://twitter.com' ;


$category = isset($_POST['category']) ? ($_POST['category']) : 'Social' ;

echo "Hi bud, thanks for submitting <b>$website</b> to the <b>$category</b> category.";
?>
This is great and now provides something more along the lines of what you’d be looking
for. If a user submits valid data to the form, and then hits the submit button, it may look like
this.
Nice Form Submission!
Hi bud, thanks for submitting Google+ to the Social category.
If the user tries to load process_form.php directly however, they are provided this
message.
Stop trying to hack the form fool!
What we are doing is checking for the presence of the submit key in the $_POST array.
The only time that key is present is if a user actually clicked on the submit button in the
form, so this is the way to most easily detect form submission.

Single Page Form Submission


Another way to approach dealing with forms and form submission in PHP is to simply
complete the form processing on the same page as the HTML form. Let’s see how to do
this.
htmlformbuiltwithlove.php
<?php

if(isset($_POST['submit']) and strlen($_POST['website']) > 0) {


$website = htmlspecialchars($_POST['website']);
$category = htmlspecialchars($_POST['category']);
echo "Hi bud, thanks for submitting <b>$website</b> to the <b>$category</b> category.";
} else {
echo 'Enter a Website and Category';
}

?>
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Built With Love</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

<form action="htmlformbuiltwithlove.php" method="post">


Website: <input type="text" name="website" value="" /><br>
Category: <input type="text" name="category" value="" /><br><br>
<input type="submit" name="submit" value="Submit Website" />
</form>

</body>
</html>

Now when this page is loaded initially, or if a blank form is submitted, the user gets the
message, Enter a Website and Category . If the user provides something like
http://facebook.com and Social then clicks submit, they will get a message like Hi bud,
thanks for submitting http://facebook.com to the Social category. Note that we added
just a minimal amount of validation in the if clause as well as running any user input
through htmlspecialchars that we learned about in the htmlentities vs
htmlspecialchars tutorial.

Basic Form Validation


In this day and age, using a PHP framework like Laravel, Symfony, Zend, Codeigniter, Yii,
or any of the many other fantastic solutions is the way to go with doing things like Form
Validation. It is still important to know the underpinnings of how these frameworks do their
magic, and in order to have that we need to understand PHP itself at the most basic levels.
So what are some of the things one would typically validate for? Let’s examine.

Validation Characteristics
• Presence Did the user actually enter anything into a given field?
• String Length Is the string provided long enough to warrant a valid value?
• Type Check Checking the type of data is quite common.
• Inclusion If there is a drop down list of 10 values, is the value provided one of those
10 possible values?
• Uniqueness Is the data a user is submitting 100% unique? This is common on email
address submissions.
• Format Does the website address contain http:// or does an email contain an @
symbol, etc..

This is the proverbial tip of the iceberg here, as data validation can have hundreds of
characteristics, but remember young Jedi, we’re talking about the basics in this episode.
So let’s see what these types of validation rules might look like in basic PHP.
<?php

// presence
$value = '';

if(!isset($value) or empty($value)) {
echo 'fail';
}

// string length
$value = '';
$min = 2;
$max = 25;

if(strlen($value) < $min) {


echo 'fail - too small';
}

if(strlen($value) > $max) {


echo 'fail - too big';
}

// type
$value = '';
if(!is_string($value)) {
echo 'fail - not a string';
}

// set inclusion
$value = '7';
$set = array('1', '2', '3', '4', '5', '6', '7', '8');
if(!in_array($value, $set)) {
echo 'fail - not in the set';
}

// format
$value = 'tom@jones.com';
if(!preg_match('/@/', $value)) {
echo 'not a valid email';
}

?>

Validation Functions
When not using a full blown framework, the next best thing is to put your validation logic
into reusable functions. Here are some examples we can use to test out on our single
page form validation example.
validation_functions.php
<?php

function has_presence($value) {
return isset($value) and $value !== '';
}

function max_length($value, $max) {


return strlen($value) <= $max;
}

function min_length($value, $min) {


return strlen($value) >= $min;
}

function has_inclusion($value, $set) {


return in_array($value, $set);
}

function form_errors($errors = array()) {


$output = '';
if(!empty($errors)){
$output .= '<div class="alert alert-danger">';
$output .= 'You might need to fix a few things!<br>';
$output .= '<ul>';
foreach($errors as $key => $error) {
$output .= '<li>'. $error .'</li>';
}
$output .= '</ul>';
$output .= '</div>';
}
return $output;
}

?>

Now we can include this file right into our form page just like this.
<?php
include('validation_functions.php');
$errors = array();

// was the form submitted?


if(isset($_POST['submit'])) {
$website = htmlspecialchars($_POST['website']);
$category = htmlspecialchars($_POST['category']);

// is the website field present?


if(!has_presence($website)) {
$errors['website'] = 'You need to enter a website!';
}

// is the website address at least 4 characters or more?


if(!min_length($website, 4)) {
$errors['minlength'] = 'The website must be 4 characters or more!';
}

// is the category field present?


if(!has_presence($category)) {
$errors['category'] = 'You need to provide a category!';
}
if(empty($errors)) {
echo "Hi bud, thanks for submitting <b>$website</b> to the <b>$category</b> category.";
}

} else {
echo 'Enter a Website and Category';
}

?>
<html>
<head>
<meta charset="utf-8">
<title>HTML Form Built With Love</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body>

<form action="htmlformbuiltwithlove.php" method="post">


Website: <input type="text" name="website" value="" /><br>
Category: <input type="text" name="category" value="" /><br><br>

<input type="submit" name="submit" value="Submit Website" />


</form>
<?php echo form_errors($errors); ?>
</body>
</html>

We now have a fully functioning HTML form which is processed via PHP on the
Fantastic!
same page, uses validation functions to handle validation, and outputs any errors in a nice
list format if something goes wrong.

PHP Cookies And Sessions


So we’ve taken a look at how you can pass data in PHP. When dealing with
URLs and Links, we’re typically working with data by way of the $_GET super
global array. If on the other hand we need to process data that has been
submitted via an HTML form, this is typically done with some form
of $_POST super global processing. There is another way to work with variable
data, and that is by using cookies and sessions. These two techniques are
immensely helpful for many reasons. One of the most important is maintaining
state. As we learned about in our fun lesson about http status codes, http is a
stateless protocol. This means it does not maintain a memory so to speak of
each request response cycle. By using sessions and cookies, this can be
overcome and web applications can be better customized to the user. Let’s
jump in!

The Importance of Cookies


Cookies as you likely know are small bits of data that get stored in your web browser. This
is what helps to store a users state. This allows the site to identify the user and recall a
specific action they have taken on the page. Cookies are also used to identify when
many HTTP requests are made by the same user. You might think an IP address would
provide this ability to determine uniqueness, but this is not the case. Think of the
thousands of users that are sitting behind a company firewall or NAT Network Address
Translation device. All of those users are going to be making requests from the same
exact IP address. Cookies are able to bring in a sense of consistency. Now cookies rely on
the HTTP protocol to even be possible. They piggyback on the request response cycle.
Web servers can not set or read cookies until a request is actually made.
Example Request Response
GET /thepage.php HTTP/1.1
Host: www.vegibit.com
Accept: */*
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: user_id=777
Here when the request is made, the sever responds with the page however in the HTTP
header it uses the Set-Cookie command to set a cookie on the users browser. The
browser then stores that cookie on the local computer for use in the future. Say the user
makes another request of a different page on the same site. This time around, when you
make the request, the HTTP GET will include any cookies for that site in the HTTP header
to the web server. A second request might then look like this.

GET /theotherpage.php HTTP/1.1


Host: www.vegibit.com
Cookie: user_id=777
Accept: */*
Notice how when this request now goes out, the web server will already know that this
request is coming from user_id 777. This is how websites remember your user name and
so on. Cookies always piggy back on the standard request response cycle. If you’re not
rocking a request response scenario, then you’re not working with any cookies. It is
because all matter of setting and reading cookies happens in the HTTP headers that get
ping ponged back and forth between the web server and the user’s browser. There is no
way to set or receive a cookie without either an HTTP request or response happening.

The $_COOKIE Super Global


Just like we learned about with $_GET and _$POST, super global variables store a range of
information in an associative array. Of course when dealing with links and URLs we’re
talking about $_GET and when dealing with form submissions we’re talking about $_POST.
When it’s time to deal with cookies, which remember are part of the HTTP request
response cycle, we can then store this information in the $_COOKIESuper Global and it
works in a similar way to the others.

Setting Cookie Values


PHP gives us a dedicated function for setting cookies. The signature looks like this.
setcookie($name, $value, $expire)
As we can see the function takes three values. A name, a value, and an expiration. The
name and value parameters are the key value pair of the name of the cookie and the value
it stores. The last argument deals with the length of time you would like the cookie to
persist. So let’s get busy setting some cookies.
<?php

$name = 'Score';
$value = 575;
$expire = time() + (60*60*24*7);
setcookie($name, $value, $expire);

?>

The first two arguments are pretty easy to deal with. The third can be a little tricky if you’re
not used to it. When setting an expiration time for a cookie, the server needs to send a
UNIX Timestamp as the value. The easiest way to do this is to have PHP generate the
current time in a UNIX Timestamp, then add the amount of time you’d like that cookie to
persist for based on the current time. UNIX Timestamps are precise to the second, so
when we add time to the timestamp, it must also be precise to the second. In other words,
when adding the length of time to the timestamp, it must be done in seconds. So if you
want a cookie to last a week, you need to provide the number seconds in a week, which is
604800. The other way to do this, which is much more common, is to use math to calculate
the amount of time you need. This is how we did it above. It helps to talk it out. We have
60 seconds in a minute, times 60 minutes in an hour, times 24 hours in a day, times seven
days in a week to arrive at the same 604800.
Note: When this PHP code executes, it will instruct the server to send this cookie in the
HTTP Response Header. This is important. Recall that headers are sent before anything
else in the page. In the absence of output buffering, this means that any time you would
like to set a cookie, you need to do so at the very top of the page so that it is included in
the header sent to the client. It is best to use cookies for non sensitive information. Since
they are freely viewable and hackable, cookies make sense for simple user experience
conveniences, but not for critical pieces of the application.

Reading Cookie Values


It is a little odd that when we talk about cookies, we are talking about them in the plural
sense. Why is this a bit odd? It is so because when we want to set and retrieve data out of
the $_COOKIE super global, note that it is singular! In any event, let’s try to take a look at the
cookie that was set in the prior snippet of code where we set Score to 575.
<?php

echo '<pre>';

print_r($_COOKIE);
?>

Array
(
[Score] => 575
)

Ah ha!Here we simply do a pretty print of the $_COOKIE super global, but in more common
use cases you would be using the actual key to retrieve the specific value you are looking
for. Let’s see an example of user preferences. We’re going to do a few different things in
this example. First off, we’re going to set the name, value, and expiration right in the
function call itself. We are also going to give these cookies a ridiculously small shelf life,
that being 5 seconds. Lastly we’ll use the actual keys of the $_COOKIE Super Global to
retrieve values only if they’re present.
<?php

// When the user makes a request to the web server


// the webserver inserts a cookie into the
// HTTP Header RESPONSE!
setcookie('Name', 'Chris', (time() + 5));
setcookie('Color', 'Blue', (time() + 5));
setcookie('Food', 'Italian', (time() + 5));

// When the user makes MULTIPLE requests to the webserver


// This code is used to check if the INCOMING REQUEST
// contains any cookies in the HTTP Header REQUEST
// If so, make use of them somehow
$name = isset($_COOKIE['Name']) ? $_COOKIE['Name'] : $_COOKIE['Name'] = 'No Value!';
$color = isset($_COOKIE['Color']) ? $_COOKIE['Color'] : $_COOKIE['Color'] = 'No Value!';
$food = isset($_COOKIE['Food']) ? $_COOKIE['Food'] : $_COOKIE['Food'] = 'No Value!';

echo 'Hi there '.$name.' - You like things that are '.$color.' in color as well as to eat '.$food.'
Food!';

?>

First Request Response Cycle


Hi there No Value! – You like things that are No Value! in color as well as to eat No
Value! Food!
Hey wait a minute, it looks like either these cookies do not exist, or they are reporting no
value within them. Let’s try the same thing again, 4 seconds later.
Hi there Chris – You like things that are Blue in color as well as to eat Italian Food!
There we go, now the values are taking place. It pays to look at the headers to see this in
action. This is what happens when loading the page for the very first time in the web
browser.
Request
http://localhost/bootstrapsandbox/cookies.php
GET /bootstrapsandbox/cookies.php HTTP/1.1
Host: localhost
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Response
HTTP/1.1 200 OK
Date: Tue, 14 Oct 2014 16:43:01 GMT
Server: Apache/2.4.4 (Win32) PHP/5.4.16
X-Powered-By: PHP/5.4.16
Set-Cookie: Name=Chris; expires=Tue, 14-Oct-2014 16:43:06 GMT
Set-Cookie: Color=Blue; expires=Tue, 14-Oct-2014 16:43:06 GMT
Set-Cookie: Food=Italian; expires=Tue, 14-Oct-2014 16:43:06 GMT
Content-Length: 100
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
Browser Output
Hi there No Value! – You like things that are No Value! in color as well as to eat No
Value! Food!

Now we can load the same page just a couple of seconds later and see the result.
Request
http://localhost/bootstrapsandbox/cookies.php
GET /bootstrapsandbox/cookies.php HTTP/1.1
Host: localhost
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: Name=Chris; Color=Blue; Food=Italian
Connection: keep-alive
Response
HTTP/1.1 200 OK
Date: Tue, 14 Oct 2014 16:48:05 GMT
Server: Apache/2.4.4 (Win32) PHP/5.4.16
X-Powered-By: PHP/5.4.16
Set-Cookie: Name=Chris; expires=Tue, 14-Oct-2014 16:48:10 GMT
Set-Cookie: Color=Blue; expires=Tue, 14-Oct-2014 16:48:10 GMT
Set-Cookie: Food=Italian; expires=Tue, 14-Oct-2014 16:48:10 GMT
Content-Length: 89
Keep-Alive: timeout=5, max=96
Connection: Keep-Alive
Content-Type: text/html
Browser Output
Hi there Chris – You like things that are Blue in color as well as to eat Italian Food!
Great!This really hammers home where cookies fit in during the request response cycle.
Note that on the first request response, we do not see the values of the cookies. This is
because it is not until at least one request is made that the server can then even set a
cookie or cookies in the first place. On the second request response cycle, the request is
carrying the cookies to the server in the header. Therefore PHP is able to hook into those
cookies on the incoming request, extract the values from them, then send the response.
The takeaway: $_COOKIE Super Global holds values from the previous request, it is not
change upon setting the cookie. Pretty slick!.

Unsetting Cookie Values


Now that we know how to set cookies and make use of them, let’s explore how to get rid of
them using PHP. It’s not quite as simple as using the unset() function that you might try on
a standard variable. Think about it, the browser checks for cookies, populates the cookie
super global, sends the request to the server, then we unset it. Well, each time the user
makes a request, she is going to re send any cookies present right back to the web server.
In order to unset a cookie then, we actually want to use setcookie() once again but in a
special way.
<pre lang="php"><?php

setcookie('Name', 'Chris', (time() + 5000));


setcookie('Color', 'Blue', (time() + 5000));
setcookie('Food', 'Italian', (time() + 5000));

echo '<pre>';

print_r($_COOKIE);

?>

Array
(
[Name] => Chris
[Color] => Blue
[Food] => Italian
)
Now if we comment out the code that set’s our cookies, we still get the value stored in
those cookies.
<?php

// setcookie('Name', 'Chris', (time() + 5000));


// setcookie('Color', 'Blue', (time() + 5000));
// setcookie('Food', 'Italian', (time() + 5000));

echo '<pre>';

print_r($_COOKIE);

?>

Array
(
[Name] => Chris
[Color] => Blue
[Food] => Italian
)

Let’s unset the Name and Food cookies now.


<?php

// setcookie('Name', 'Chris', (time() + 5000));


// setcookie('Color', 'Blue', (time() + 5000));
// setcookie('Food', 'Italian', (time() + 5000));

setcookie('Name', null, time() - 3600);


setcookie('Food', null, time() - 3600);

echo '<pre>';

print_r($_COOKIE);

?>

Array
(
[Color] => Blue
)

Smashing! By passing in a value of null to the second parameter and a time in the past to the
third parameter, we can successfully remove cookies from the user’s browser. Just note
that it is the second request where this actually takes effect.

Sessions In PHP
Sessions are really great tools for managing state and they are related to cookies. The key
difference is that when you think of a session, you should think server side. Cookies are
strictly browser side. A session is a file that is actually stored on the web server. The web
server then sends a cookie to the user that references that session file. You see how that
works? It’s like a two step process where the file on the server and the cookie in the
browser work together to maintain state or share information. There are a few pros and
cons to each approach so lets take a look at them.
Session Pros

• More Storage A cookie can only hold about 4000 characters maximum. You can go
further than this as needed with sessions.
• Smaller Request Sizes By storing the session on the server, there is no need to put
all of this data in the cookie itself for every HTTP Request.
• Hides Data Values You can’t read the value of a session cookie like you can with a
standard cookie in the browser.
• More Secure Since values are hidden, they are less prone to hacking.

Session Cons

• Slower to access They are a tiny bit slower, however you’ll never notice it. We’re
talking milliseconds here.
• Expire Immediately Upon Browser Close Once a user closes their browser, the
session ends.
• Session Files Accumulate Since sessions don’t really expire, they tend to build up
on the web server. They will need to be manually deleted over time.

One thing to be aware of with Sessions in PHP is that the values can be set and retrieved
in the same request response cycle. We saw this is not possible by using standard
cookies. Why is this? This is because with regular cookies, the web server must reach out
to the users browser over HTTP to actually set or get values from cookies. With sessions,
this step can be eliminated. PHP and the web server work directly with a session file
stored on the web server itself, then a cookie gets sent back to the user with a reference to
that file. In many ways, this makes sessions actually easier to use, you don’t have to think
as much. In fact, when storing values in the $_SESSION Super Global, all you have to do is
make up and names you like for the keys, then assign the values you want as needed.
Let’s see an example.
<?php
session_start();

echo '<pre>';

$_SESSION['boo'] = 'yeah';
$_SESSION['hip'] = 'hop';
$_SESSION['ying'] = 'yang';

print_r($_SESSION);

?>
Array
(
[boo] => yeah
[hip] => hop
[ying] => yang
)

PHP Cookies Vs Sessions Summary


Hopefully after reading this tutorial you have a better understanding of how cookies and
sessions work in PHP. The main takeaways are that cookies live on the users browser
while session files live on the server file system. Sessions still use cookies, but it is only to
provide a PHP Session ID, or a reference to the Session file that lives on the server.

PHP And MySQL Tutorial

This PHP Tutorial Series has gone soup to nuts covering all of the fundamental
aspects of using PHP to build dynamic websites. Based on all of the concepts
covered so far, you should be able to build links to pages, pass data
via $_GET in those links, create forms, collect user data via $_POST in those
forms, as well as use cookies and sessions to establish state and customized
user experiences. One thing we haven’t talked about yet is working
with MySQL in PHP. A fantastic place to start if you are new to MySQL is right
at our dedicated 10 Part MySQL Tutorial Series. That will give you a fantastic
foundation on which to build upon for working with MySQL in PHP. In this part
of our PHP Tutorial Series, we’ll take a look at MySQL in terms of using PHP to
read and write data, store data, organize data, as well as set up relationships of
data.
Database APIs in PHP
First off let’s talk a little bit about database apis in PHP. In plain vanilla terms we have
three options that are built into the PHP language. The first is mysql, which is the original
MySQL api for PHP. The next option is mysqli, which is the MySQL Improved version of
the api. Lastly, PHP has PDO, or PHP Data Objects. In reality, the old mysql can be largely
ignored unless you are tasked with maintaining a legacy code base. In the current web
development world you’ll be using either mysqli or PDO. Let’s look at a chart to view the
differences between the three.
mysql mysqli PDO

Introduced v2.0 v5.0 v5.1

Deprecated v5.5

Built in to PHP Yes Yes Yes

Pre configured for MySQL Yes Yes No

Databases besides MySQL supported? No No Yes

Proecdural Syntax Yes Yes No

Object Oriented Syntax No Yes Yes

Support For Prepared Statements No Yes Yes

This is a great overview of your options of using PHP to interact with your database. In this
episode we’re going to look at mysqli and focus on the procedural approach. This is not to
say that you can not use mysqli in an object oriented approach, you very much can. In fact
let’s compare the two approaches side by side.
mysqli Procedural Syntax mysqli OOP syntax

mysqli_connect $mysqli = new mysqli


mysqli_connect_errno $mysqli->connect_errno

mysqli_connect_error $mysqli->connect_error

mysqli_real_escape_string $mysqli->real_escape_string

mysqli_query $mysqli->query

mysqli_fetch_assoc $mysqli->fetch_assoc

mysqli_close $mysqli->close

The 5 Steps
Now that we have a bit of a high level overview, let’s look at the five steps of database
connectivity in PHP. These five steps are really the bread and butter of connecting to your
database and you will use this approach no matter what type of interface you choose, so it
makes sense to understand the concept of each step. This will make you a better
programmer and give you a better ability to troubleshoot issues when things don’t quite go
the way you had planned.

• 1. Create The Database Connection. You can think of this step almost like picking
up a telephone and making a call to someone. Once that call is established, you
have a valid connection. The same idea applies when dealing with databases.
• 2. Perform A Query. With your knowledge of MySQL, you can now begin running
queries using SELECT INSERT UPDATE and DELETE in addition to the other
commands available.
• 3. Make Use of Data Retrieved. In the case of getting back any data from a query,
you can make use of that data. It may involve emailing that data to someone or just
outputting it to the screen.
• 4. Release Memory. Once you’re done with the prior operation, it’s time to release
any memory that was used to hold the data from step 3.
• 5. Close The Connection. Once the conversation between PHP and the Database
is complete, you need to close the connection. This is much like hanging up the
telephone once your conversation is complete.

Opening and Closing Connections


We have the 5 concepts down. Now let’s look at the commands in PHP that make this
happen. First up we’ll focus on steps 1 and 5 since we need to know how to open and
close connections before we can do anything else. The commands you’ll need
are mysqli_connect, mysqli_connect_errno, mysqli_connect_error, and mysqli_close.
database_connect.php
<?php

// open a connection
$dhost = 'localhost';
$duser = 'root';
$dpw = '';
$dname = 'wordpress';
$connection = mysqli_connect($dhost, $duser, $dpw, $dname);

// test the connection


if(mysqli_connect_errno()){
die('Something went wrong with the database<br><br> '
. mysqli_connect_error() . ':'
. mysqli_connect_errno());
} else {
var_dump($connection);
}

// close the connection


if(mysqli_close($connection) == true) {
echo 'Database connection closed.';
}

?>

This is what you get when everything goes right, an object of type mysqli.
object(mysqli)[1]
public 'affected_rows' => null
public 'client_info' => null
public 'client_version' => null
public 'connect_errno' => null
public 'connect_error' => null
public 'errno' => null
public 'error' => null
public 'error_list' => null
public 'field_count' => null
public 'host_info' => null
public 'info' => null
public 'insert_id' => null
public 'server_info' => null
public 'server_version' => null
public 'stat' => null
public 'sqlstate' => null
public 'protocol_version' => null
public 'thread_id' => null
public 'warning_count' => null

Database connection closed.


Now what happens when things go wrong? Let’s see what happens if we change the
credentials for each parameter.
Wrong Host
Something went wrong with the database

php_network_getaddresses: getaddrinfo failed: No such host is known. :2002

Script ended unexpectedly.

Wrong User
Something went wrong with the database

Access denied for user ''@'localhost' to database 'wordpress':1044

Script ended unexpectedly.

Wrong Password
Something went wrong with the database

Access denied for user 'root'@'localhost' (using password: YES):1045

Script ended unexpectedly.

Wrong Database Name


Something went wrong with the database

Unknown database 'imaginary_database':1049

Script ended unexpectedly.

It is human nature to jump right into things and say, “Hey! What could possibly go wrong?!”
We know that things can and do go wrong, so it’s best to include the code that can output
some useful information to you so that you understand the problem.

Retrieve Data From MySQL Using PHP


You made it past the connection phase. MySQL gave you a green light and said you’re
good to go. Now that you are able to get into the database, you need to actually execute
some commands to find useful data. Let’s start with mysqli_query, mysqli_fetch_row,
and mysqli_free_result. In this example we’re going to fetch all posts from a wordpress
database and just var_dump each result to the screen.
<?php

// Step 1
// open a connection
$dhost = 'localhost';
$duser = 'root';
$dpw = '';
$dname = 'wordpress';
$connection = mysqli_connect($dhost, $duser, $dpw, $dname);

// Step 2
// test the connection
if(mysqli_connect_errno()){
die('Something went wrong with the database<br><br> '
. mysqli_connect_error() . ':'
. mysqli_connect_errno());
}

// Step 3
// define the query
$query1 = "select * from wp_posts";

// build up the query style


$query2 = "SELECT * ";
$query2 .= "FROM `wp_posts` ";
$query2 .= "WHERE `post_title` LIKE '%laravel%' ";
$query2 .= "LIMIT 0 , 30 ";

// Step 4
// run the query to get a resource placed in $result
$result = mysqli_query($connection, $query2);

// Step 5
// test to see if the query was successful
if(!$result) {
die('The query was not successful.');
} else {
// Step 6
// the query was successful so let's get the data if there is some
// as long as there is another row in the $result, assign it to $row
while($row = mysqli_fetch_row($result)) {
// output each row
var_dump($row);
}

// Step 7
// Release the returned data
mysqli_free_result($result);
}

// Step 8
// close the connection
if(mysqli_close($connection) == true) {
echo 'Database connection closed.';
}

?>

Note that we use two styles to build up the query. If you like you can simply build the query
in one big long string as we do in $query1, or, you can incrementally build the query string
using the .= operator like we did with $query2. This sometimes helps to be able to ‘think
out’ your query so to speak.
Now we can see why PHP frameworks are so popular. All of this leg work is done pretty
much automagically for you. When using raw PHP, you’re going to need to write all of this
code to talk to and work with the database. In truth however, it is super important that you
can actually do this work using raw PHP for if you can’t, you will be dead in the water if
something goes wrong on you when you’re using a framework. This is because you won’t
have even the slightest clue as to how the framework might be handling the native code for
you. So let’s review the basic idea of the steps needed to make a query.

Make A Database Connection


$connection = mysqli_connect( $dhost , $duser , $dpw , $dname )

Test The Connection


mysqli_connect_errno()
mysqli_connect_error()

Run A Query
$result = mysqli_query( $connection , 'select * from wp_posts' );

Extract Data From Query Result


mysqli_fetch_row( $result )

Free The Memory


mysqli_free_result( $result )
Close The Database Connection
mysqli_close( $connection )

Conclusion
There you have it friends, everything you need to use native PHP to work with a MySQL
database. Yes, it almost seems like a lost art in these days of Hyper Capable Modern PHP
Frameworks, but it pays to come back to basics to make sure the foundation is solid.

Process Returned MySQL Query Results In


PHP

In the prior episode of working with MySQL and PHP, we took a good look at
the entire process of getting data to work with. This involved setting up a
database connection, testing the database connection, defining a query,
running said query, processing any results we got back, releasing memory, and
closing the database connection. Bing, Bang, Boom, we’re talking to the
database successfully. In this PHP and MySQL Tutorial we’ll take a closer look
at the processing portion of this cycle. So far we have only looked
at mysqli_fetch_row, but now we’ll take a look
at mysqli_fetch_assoc, mysqli_fetch_array, and mysqli_fetch_object as
well. There are some similarities and differences between the various
approaches so we’ll examine those as well. Let’s jump in!
Processing Returned Query Data
There are four ways to process the data we get back from a query. The first approach is
simply using the mysqli_fetch_row option. This retrieves a row of data from the database
and assigns it to a standard array. There is nothing fancy about this array, and the keys of
this array are simply 0 based integers. For example this query will return three rows of data
from the wp_posts table of a WordPress database.

1. mysqli_fetch_row
<?php

// Step 1
// open a connection
$dhost = 'localhost';
$duser = 'root';
$dpw = '';
$dname = 'wordpress';
$connection = mysqli_connect($dhost, $duser, $dpw, $dname);

// Step 2
// test the connection
if(mysqli_connect_errno()){
die('Something went wrong with the database<br><br> '
. mysqli_connect_error() . ':'
. mysqli_connect_errno());
}

// Step 3
// define the query
$query1 = "select * from wp_posts";

// build up the query style


$query2 = "SELECT * ";
$query2 .= "FROM `wp_posts` ";
$query2 .= "WHERE `post_title` LIKE '%laravel%' ";
$query2 .= "LIMIT 0 , 3 ";

// Step 4
// run the query to get a resource placed in $result
$result = mysqli_query($connection, $query2);

// Step 5
// test to see if the query was successful
if(!$result) {
die('The query was not successful.');
} else {
// Step 6
// the query was successful so let's get the data if there is some
// as long as there is another row in the $result, assign it to $row
while($row = mysqli_fetch_row($result)) {
// output each row
var_dump($row);
}

// Step 7
// Release the returned data
mysqli_free_result($result);
}

// Step 8
// close the connection
if(mysqli_close($connection) == true) {
echo 'Database connection closed.';
}

?>

Here is the output of your three posts. Notice that each key in the array is just an integer
which is not exactly the most helpful way of identifying what you are dealing with. A pro is
that this approach is the fastest of all options.
array (size=23)
0 => string '3518' (length=4)
1 => string '1' (length=1)
2 => string '2014-01-07 21:51:27' (length=19)
3 => string '2014-01-07 21:51:27' (length=19)
4 => string '' (length=9243)
5 => string 'Install Laravel on Windows' (length=26)
6 => string '' (length=0)
7 => string 'publish' (length=7)
8 => string 'open' (length=4)
9 => string 'open' (length=4)
10 => string '' (length=0)
11 => string 'install-laravel-on-windows' (length=26)
12 => string '' (length=0)
13 => string '' (length=0)
14 => string '2014-01-07 21:51:27' (length=19)
15 => string '2014-01-07 21:51:27' (length=19)
16 => string '' (length=0)
17 => string '0' (length=1)
18 => string 'http://vegibit.com/?p=3518' (length=26)
19 => string '0' (length=1)
20 => string 'post' (length=4)
21 => string '' (length=0)
22 => string '9' (length=1)

array (size=23)
0 => string '3582' (length=4)
1 => string '1' (length=1)
2 => string '2014-01-20 20:33:01' (length=19)
3 => string '2014-01-20 20:33:01' (length=19)
4 => string '' (length=7009)
5 => string 'Crud In Laravel 4' (length=17)
6 => string '' (length=0)
7 => string 'publish' (length=7)
8 => string 'open' (length=4)
9 => string 'open' (length=4)
10 => string '' (length=0)
11 => string 'crud-in-laravel-4' (length=17)
12 => string '' (length=0)
13 => string '' (length=0)
14 => string '2014-01-20 20:33:01' (length=19)
15 => string '2014-01-20 20:33:01' (length=19)
16 => string '' (length=0)
17 => string '0' (length=1)
18 => string 'http://vegibit.com/?p=3582' (length=26)
19 => string '0' (length=1)
20 => string 'post' (length=4)
21 => string '' (length=0)
22 => string '5' (length=1)

array (size=23)
0 => string '3658' (length=4)
1 => string '1' (length=1)
2 => string '2014-01-25 03:11:55' (length=19)
3 => string '2014-01-25 03:11:55' (length=19)
4 => string '' (length=29)
6 => string '' (length=0)
7 => string 'publish' (length=7)
8 => string 'open' (length=4)
9 => string 'open' (length=4)
10 => string '' (length=0)
11 => string 'laravel-eloquent-orm-tutorial-2' (length=31)
12 => string '' (length=0)
13 => string '' (length=0)
14 => string '2014-01-25 03:11:55' (length=19)
15 => string '2014-01-25 03:11:55' (length=19)
16 => string '' (length=0)
17 => string '0' (length=1)
18 => string 'http://vegibit.com/?p=3658' (length=26)
19 => string '0' (length=1)
20 => string 'post' (length=4)
21 => string '' (length=0)
22 => string '6' (length=1)

2. mysqli_fetch_assoc
An easier way to work with the data is to be able to have the database field names be the
key names of the array. To do this, you can simply use mysqli_fetch_assocfunction.
Simply update the while loop to use this function like so.
<?php

while($row = mysqli_fetch_assoc($result)) {
// output each row
var_dump($row);
}

Now here are the three posts and notice that the keys of the array are nice descriptive
names. These are the field names from the table you pulled the data from. So the
difference between mysqli_fetch_row and mysqli_fetch_assoc is
that mysqli_fetch_row places results into a standard
array and mysqli_fetch_assoc places results into an associative array.
array (size=23)
'ID' => string '3518' (length=4)
'post_author' => string '1' (length=1)
'post_date' => string '2014-01-07 21:51:27' (length=19)
'post_date_gmt' => string '2014-01-07 21:51:27' (length=19)
'post_content' => string ''(length=9243)
'post_title' => string 'Install Laravel on Windows' (length=26)
'post_excerpt' => string '' (length=0)
'post_status' => string 'publish' (length=7)
'comment_status' => string 'open' (length=4)
'ping_status' => string 'open' (length=4)
'post_password' => string '' (length=0)
'post_name' => string 'install-laravel-on-windows' (length=26)
'to_ping' => string '' (length=0)
'pinged' => string '' (length=0)
'post_modified' => string '2014-01-07 21:51:27' (length=19)
'post_modified_gmt' => string '2014-01-07 21:51:27' (length=19)
'post_content_filtered' => string '' (length=0)
'post_parent' => string '0' (length=1)
'guid' => string 'http://vegibit.com/?p=3518' (length=26)
'menu_order' => string '0' (length=1)
'post_type' => string 'post' (length=4)
'post_mime_type' => string '' (length=0)
'comment_count' => string '9' (length=1)

array (size=23)
'ID' => string '3582' (length=4)
'post_author' => string '1' (length=1)
'post_date' => string '2014-01-20 20:33:01' (length=19)
'post_date_gmt' => string '2014-01-20 20:33:01' (length=19)
'post_content' => string '' (length=7009)
'post_title' => string 'Crud In Laravel 4' (length=17)
'post_excerpt' => string '' (length=0)
'post_status' => string 'publish' (length=7)
'comment_status' => string 'open' (length=4)
'ping_status' => string 'open' (length=4)
'post_password' => string '' (length=0)
'post_name' => string 'crud-in-laravel-4' (length=17)
'to_ping' => string '' (length=0)
'pinged' => string '' (length=0)
'post_modified' => string '2014-01-20 20:33:01' (length=19)
'post_modified_gmt' => string '2014-01-20 20:33:01' (length=19)
'post_content_filtered' => string '' (length=0)
'post_parent' => string '0' (length=1)
'guid' => string 'http://vegibit.com/?p=3582' (length=26)
'menu_order' => string '0' (length=1)
'post_type' => string 'post' (length=4)
'post_mime_type' => string '' (length=0)
'comment_count' => string '5' (length=1)

array (size=23)
'ID' => string '3658' (length=4)
'post_author' => string '1' (length=1)
'post_date' => string '2014-01-25 03:11:55' (length=19)
'post_date_gmt' => string '2014-01-25 03:11:55' (length=19)
'post_content' => string ''(length=16826)
'post_title' => string 'Laravel Eloquent ORM Tutorial' (length=29)
'post_excerpt' => string '' (length=0)
'post_status' => string 'publish' (length=7)
'comment_status' => string 'open' (length=4)
'ping_status' => string 'open' (length=4)
'post_password' => string '' (length=0)
'post_name' => string 'laravel-eloquent-orm-tutorial-2' (length=31)
'to_ping' => string '' (length=0)
'pinged' => string '' (length=0)
'post_modified' => string '2014-01-25 03:11:55' (length=19)
'post_modified_gmt' => string '2014-01-25 03:11:55' (length=19)
'post_content_filtered' => string '' (length=0)
'post_parent' => string '0' (length=1)
'guid' => string 'http://vegibit.com/?p=3658' (length=26)
'menu_order' => string '0' (length=1)
'post_type' => string 'post' (length=4)
'post_mime_type' => string '' (length=0)
'comment_count' => string '6' (length=1)

3. mysqli_fetch_array
The third option for you if you’re unable to make up your mind which of the first two are
better, is to use the mysqli_fetch_array. Why you say? Because this function returns both
index based and associative style in one big array. We’ll update the while loop one more
time, then output the results. Note that this approach is probably not ideal since it is more
computational and memory intensive for no real gain.
<?php

while($row = mysqli_fetch_array($result)) {
// output each row
var_dump($row);
}
Once again, here are the three posts with the output processed by mysqli_fetch_array
array (size=46)
0 => string '3518' (length=4)
'ID' => string '3518' (length=4)
1 => string '1' (length=1)
'post_author' => string '1' (length=1)
2 => string '2014-01-07 21:51:27' (length=19)
'post_date' => string '2014-01-07 21:51:27' (length=19)
3 => string '2014-01-07 21:51:27' (length=19)
'post_date_gmt' => string '2014-01-07 21:51:27' (length=19)
4 => string ''(length=9243)
'post_content' => string '' (length=9243)
5 => string 'Install Laravel on Windows' (length=26)
'post_title' => string 'Install Laravel on Windows' (length=26)
6 => string '' (length=0)
'post_excerpt' => string '' (length=0)
7 => string 'publish' (length=7)
'post_status' => string 'publish' (length=7)
8 => string 'open' (length=4)
'comment_status' => string 'open' (length=4)
9 => string 'open' (length=4)
'ping_status' => string 'open' (length=4)
10 => string '' (length=0)
'post_password' => string '' (length=0)
11 => string 'install-laravel-on-windows' (length=26)
'post_name' => string 'install-laravel-on-windows' (length=26)
12 => string '' (length=0)
'to_ping' => string '' (length=0)
13 => string '' (length=0)
'pinged' => string '' (length=0)
14 => string '2014-01-07 21:51:27' (length=19)
'post_modified' => string '2014-01-07 21:51:27' (length=19)
15 => string '2014-01-07 21:51:27' (length=19)
'post_modified_gmt' => string '2014-01-07 21:51:27' (length=19)
16 => string '' (length=0)
'post_content_filtered' => string '' (length=0)
17 => string '0' (length=1)
'post_parent' => string '0' (length=1)
18 => string 'http://vegibit.com/?p=3518' (length=26)
'guid' => string 'http://vegibit.com/?p=3518' (length=26)
19 => string '0' (length=1)
'menu_order' => string '0' (length=1)
20 => string 'post' (length=4)
'post_type' => string 'post' (length=4)
21 => string '' (length=0)
'post_mime_type' => string '' (length=0)
22 => string '9' (length=1)
'comment_count' => string '9' (length=1)

array (size=46)
0 => string '3582' (length=4)
'ID' => string '3582' (length=4)
1 => string '1' (length=1)
'post_author' => string '1' (length=1)
2 => string '2014-01-20 20:33:01' (length=19)
'post_date' => string '2014-01-20 20:33:01' (length=19)
3 => string '2014-01-20 20:33:01' (length=19)
'post_date_gmt' => string '2014-01-20 20:33:01' (length=19)
4 => string ''(length=7009)
'post_content' => string ''(length=7009)
5 => string 'Crud In Laravel 4' (length=17)
'post_title' => string 'Crud In Laravel 4' (length=17)
6 => string '' (length=0)
'post_excerpt' => string '' (length=0)
7 => string 'publish' (length=7)
'post_status' => string 'publish' (length=7)
8 => string 'open' (length=4)
'comment_status' => string 'open' (length=4)
9 => string 'open' (length=4)
'ping_status' => string 'open' (length=4)
10 => string '' (length=0)
'post_password' => string '' (length=0)
11 => string 'crud-in-laravel-4' (length=17)
'post_name' => string 'crud-in-laravel-4' (length=17)
12 => string '' (length=0)
'to_ping' => string '' (length=0)
13 => string '' (length=0)
'pinged' => string '' (length=0)
14 => string '2014-01-20 20:33:01' (length=19)
'post_modified' => string '2014-01-20 20:33:01' (length=19)
15 => string '2014-01-20 20:33:01' (length=19)
'post_modified_gmt' => string '2014-01-20 20:33:01' (length=19)
16 => string '' (length=0)
'post_content_filtered' => string '' (length=0)
17 => string '0' (length=1)
'post_parent' => string '0' (length=1)
18 => string 'http://vegibit.com/?p=3582' (length=26)
'guid' => string 'http://vegibit.com/?p=3582' (length=26)
19 => string '0' (length=1)
'menu_order' => string '0' (length=1)
20 => string 'post' (length=4)
'post_type' => string 'post' (length=4)
21 => string '' (length=0)
'post_mime_type' => string '' (length=0)
22 => string '5' (length=1)
'comment_count' => string '5' (length=1)

array (size=46)
0 => string '3658' (length=4)
'ID' => string '3658' (length=4)
1 => string '1' (length=1)
'post_author' => string '1' (length=1)
2 => string '2014-01-25 03:11:55' (length=19)
'post_date' => string '2014-01-25 03:11:55' (length=19)
3 => string '2014-01-25 03:11:55' (length=19)
'post_date_gmt' => string '2014-01-25 03:11:55' (length=19)
4 => string ''(length=16826)
'post_content' => string ''(length=16826)
5 => string 'Laravel Eloquent ORM Tutorial' (length=29)
'post_title' => string 'Laravel Eloquent ORM Tutorial' (length=29)
6 => string '' (length=0)
'post_excerpt' => string '' (length=0)
7 => string 'publish' (length=7)
'post_status' => string 'publish' (length=7)
8 => string 'open' (length=4)
'comment_status' => string 'open' (length=4)
9 => string 'open' (length=4)
'ping_status' => string 'open' (length=4)
10 => string '' (length=0)
'post_password' => string '' (length=0)
11 => string 'laravel-eloquent-orm-tutorial-2' (length=31)
'post_name' => string 'laravel-eloquent-orm-tutorial-2' (length=31)
12 => string '' (length=0)
'to_ping' => string '' (length=0)
13 => string '' (length=0)
'pinged' => string '' (length=0)
14 => string '2014-01-25 03:11:55' (length=19)
'post_modified' => string '2014-01-25 03:11:55' (length=19)
15 => string '2014-01-25 03:11:55' (length=19)
'post_modified_gmt' => string '2014-01-25 03:11:55' (length=19)
16 => string '' (length=0)
'post_content_filtered' => string '' (length=0)
17 => string '0' (length=1)
'post_parent' => string '0' (length=1)
18 => string 'http://vegibit.com/?p=3658' (length=26)
'guid' => string 'http://vegibit.com/?p=3658' (length=26)
19 => string '0' (length=1)
'menu_order' => string '0' (length=1)
20 => string 'post' (length=4)
'post_type' => string 'post' (length=4)
21 => string '' (length=0)
'post_mime_type' => string '' (length=0)
22 => string '6' (length=1)
'comment_count' => string '6' (length=1)

4. mysqli_fetch_object
Last up is the ability to fetch rows as objects using the mysqli_fetch_object function. Note
the updated syntax and associated updated output of our query for three posts in a
WordPress database.
<?php

while($row = mysqli_fetch_object($result)) {
// output each row
var_dump($row);
}

object(stdClass)[3]
public 'ID' => string '3518' (length=4)
public 'post_author' => string '1' (length=1)
public 'post_date' => string '2014-01-07 21:51:27' (length=19)
public 'post_date_gmt' => string '2014-01-07 21:51:27' (length=19)
public 'post_content' => string ''(length=9243)
public 'post_title' => string 'Install Laravel on Windows' (length=26)
public 'post_excerpt' => string '' (length=0)
public 'post_status' => string 'publish' (length=7)
public 'comment_status' => string 'open' (length=4)
public 'ping_status' => string 'open' (length=4)
public 'post_password' => string '' (length=0)
public 'post_name' => string 'install-laravel-on-windows' (length=26)
public 'to_ping' => string '' (length=0)
public 'pinged' => string '' (length=0)
public 'post_modified' => string '2014-01-07 21:51:27' (length=19)
public 'post_modified_gmt' => string '2014-01-07 21:51:27' (length=19)
public 'post_content_filtered' => string '' (length=0)
public 'post_parent' => string '0' (length=1)
public 'guid' => string 'http://vegibit.com/?p=3518' (length=26)
public 'menu_order' => string '0' (length=1)
public 'post_type' => string 'post' (length=4)
public 'post_mime_type' => string '' (length=0)
public 'comment_count' => string '9' (length=1)

object(stdClass)[4]
public 'ID' => string '3582' (length=4)
public 'post_author' => string '1' (length=1)
public 'post_date' => string '2014-01-20 20:33:01' (length=19)
public 'post_date_gmt' => string '2014-01-20 20:33:01' (length=19)
public 'post_content' => string ''(length=7009)
public 'post_title' => string 'Crud In Laravel 4' (length=17)
public 'post_excerpt' => string '' (length=0)
public 'post_status' => string 'publish' (length=7)
public 'comment_status' => string 'open' (length=4)
public 'ping_status' => string 'open' (length=4)
public 'post_password' => string '' (length=0)
public 'post_name' => string 'crud-in-laravel-4' (length=17)
public 'to_ping' => string '' (length=0)
public 'pinged' => string '' (length=0)
public 'post_modified' => string '2014-01-20 20:33:01' (length=19)
public 'post_modified_gmt' => string '2014-01-20 20:33:01' (length=19)
public 'post_content_filtered' => string '' (length=0)
public 'post_parent' => string '0' (length=1)
public 'guid' => string 'http://vegibit.com/?p=3582' (length=26)
public 'menu_order' => string '0' (length=1)
public 'post_type' => string 'post' (length=4)
public 'post_mime_type' => string '' (length=0)
public 'comment_count' => string '5' (length=1)

object(stdClass)[3]
public 'ID' => string '3658' (length=4)
public 'post_author' => string '1' (length=1)
public 'post_date' => string '2014-01-25 03:11:55' (length=19)
public 'post_date_gmt' => string '2014-01-25 03:11:55' (length=19)
public 'post_content' => string ''(length=16826)
public 'post_title' => string 'Laravel Eloquent ORM Tutorial' (length=29)
public 'post_excerpt' => string '' (length=0)
public 'post_status' => string 'publish' (length=7)
public 'comment_status' => string 'open' (length=4)
public 'ping_status' => string 'open' (length=4)
public 'post_password' => string '' (length=0)
public 'post_name' => string 'laravel-eloquent-orm-tutorial-2' (length=31)
public 'to_ping' => string '' (length=0)
public 'pinged' => string '' (length=0)
public 'post_modified' => string '2014-01-25 03:11:55' (length=19)
public 'post_modified_gmt' => string '2014-01-25 03:11:55' (length=19)
public 'post_content_filtered' => string '' (length=0)
public 'post_parent' => string '0' (length=1)
public 'guid' => string 'http://vegibit.com/?p=3658' (length=26)
public 'menu_order' => string '0' (length=1)
public 'post_type' => string 'post' (length=4)
public 'post_mime_type' => string '' (length=0)
public 'comment_count' => string '6' (length=1)

Drilling Down on Results


In the examples above, we simply used a var_dump to dump out the entire contents of the
query results to the screen. This is not what you are likely going to do in your applications.
Sure it’s great for troubleshooting and debugging, but it makes much more sense to strictly
access only the data you want to work with. Let’s try this out with
the mysqli_fetch_assoc function.
<?php

// Step 1
// open a connection
$dhost = 'localhost';
$duser = 'root';
$dpw = '';
$dname = 'wordpress';
$connection = mysqli_connect($dhost, $duser, $dpw, $dname);

// Step 2
// test the connection
if(mysqli_connect_errno()){
die('Something went wrong with the database<br><br> '
. mysqli_connect_error() . ':'
. mysqli_connect_errno());
}

// Step 3
// define the query
$query1 = "select * from wp_posts";
// build up the query style
$query2 = "SELECT * ";
$query2 .= "FROM `wp_posts` ";
$query2 .= "WHERE `post_title` LIKE '%laravel%' ";
$query2 .= "LIMIT 0 , 3 ";

// Step 4
// run the query to get a resource placed in $result
$result = mysqli_query($connection, $query2);

// Step 5
// test to see if the query was successful
if(!$result) {
die('The query was not successful.');
} else {
// Step 6
// the query was successful so let's get the data if there is some
// as long as there is another row in the $result, assign it to $row
while($post = mysqli_fetch_assoc($result)) {
// output each row
echo 'The post ID is '.$post['ID'].'<br>';
echo 'The post title is '.$post['post_title'].'<br><br>';
}

// Step 7
// Release the returned data
mysqli_free_result($result);
}

// Step 8
// close the connection
if(mysqli_close($connection) == true) {
echo 'Database connection closed.';
}

?>

The post ID is 3518


The post title is Install Laravel on Windows

The post ID is 3582


The post title is Crud In Laravel 4

The post ID is 3658


The post title is Laravel Eloquent ORM Tutorial

Look at how much nicer that is to look at! Also note that instead of assigning the results to
a $row variable, we assign the results to a $post variable. Since we are dealing with posts
in WordPress database, it makes sense to name things this way. If you were querying an
orders table, you might assign the results to an $order variable, and so on. This is to give
some indication to yourself and anyone else who needs to review the code of what you are
actually dealing with.

Conclusion
In this particular adventure in our PHP and MySQL tutorial series, we took a look at the
four different ways to process query results. We looked
at mysqli_fetch_row, mysqli_fetch_assoc, mysqli_fetch_array,
and mysqli_fetch_object as ways to loop through your results and output them or
process them as needed.

PHP MySQL CRUD Tutorial

In the last lesson we learned more about working with results from select
queries in MySQL. In other words, when we used PHP to build up a query and
send it to MySQL, MySQL then sent back a resource which could be massaged
by any of the four techniques we discussed to get access to the data contained
in the resource. So of all the MySQL commands such
as SELECT, INSERT, UPDATE, and DELETE, SELECT is the only one to return a
resource on success which requires further processing. The other commands
simply return either true or false on a successful query or failed query
respectively. In this episode, we’ll continue working with the database and build
on the prior lessons concepts. We’ll now start completing inserts, updates, and
deletes as well. Let’s get to it!
What Does A Query Return?
First off, let’s take a look at the different scenarios for what we can expect when actually
executing the query against MySQL. A query is either going to succeed or fail, and the
table here shows each of the possible 8 scenarios you may have.
Query Success Query Failure

SELECT resource false

INSERT true false

UPDATE true false

DELETE true false

What this tells us is that the SELECT is going to strictly follow the 5 step process which is to:

• 1. Create The Database Connection.


• 2. Perform A Query.
• 3. Make Use of Data Retrieved.
• 4. Release Memory.
• 5. Close The Connection.

All other cases for INSERT, UPDATE, and DELETE, are only going to require 3 steps. Those
would be 1, 2, and 5 like so:

• 1. Create The Database Connection.


• 2. Perform A Query.
• 5. Close The Connection.

How Do You MySQL Insert With PHP?


With this knowledge, lets create an insert statement into a database table. We’ll use a links
table, here is the sql to create it:
CREATE TABLE `links` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`url` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1

<?php
// 1
// open a connection
$dhost = 'localhost';
$duser = 'root';
$dpw = '';
$dname = 'bookmarks';
$connection = mysqli_connect($dhost, $duser, $dpw, $dname);

// test the connection


if(mysqli_connect_errno()){
die('Something went wrong with the database<br><br> '
. mysqli_connect_error() . ':'
. mysqli_connect_errno());
}

// 2
// define the query
// we'll pretend these are coming from a form via $_POST
$url = 'http://yahoo.com';
$name = 'Yahoo';

$query = "insert into links ( url, name )


values ( '$url', '$name' )";

// run the query


$result = mysqli_query($connection, $query);

// test to see if the query was successful


if($result) {
echo 'The Query Worked!<br>';
} else {
die('Look at this error - '. mysqli_error($connection));
}

// create a new query


$query = 'select * from links';

// run the new query


$result = mysqli_query($connection, $query);

// while there are bookmarks, echo them out


while($bookmark = mysqli_fetch_assoc($result)){
echo $bookmark['name'].' lives at '.$bookmark['url'].'<br>';
}

// 5
// close the connection
if(mysqli_close($connection) == true) {
echo 'Database connection closed.';
}

?>

The Query Worked!


VegiBit lives at http://vegibit.com
Yahoo lives at http://yahoo.com
Database connection closed.

Slick!This is a good example of being able to open one database connection at the top of
the page, run multiple queries as needed in the body of the page, then close the database
connection at the very end. In this example, ran this page two times. Once with the
variable values of $url = 'http://yahoo.com'; and $name = 'Yahoo';while the second
query contained $url = 'http://vegibit.com'; and $name = 'VegiBit';. Once the
connection was opened, we first did a query using the INSERT statement to put bookmark
into our links table. Further down the page, but before the database connection was
closed, we ran another query using the SELECT statement to immediately read back the
data we just inserted. Once we did all of this, we simply closed the database connection.

mysqli_insert_id
Typically when doing inserts into a MySQL database, you’ll have an ID field that auto
increments on each new insert. You never specify the value of this field, MySQL does it all
automatically for you. The problem however, is that this field is also typically the unique
identifier for a specific row or record of data in the table. How often do you hear something
like, find by ID? If you are entering new records into the database, and you’re not
specifying what their ID is, then how in the world will you find out this information? You’ll
find this out with the mysqli_insert_id() function, and it is a critical function to be aware
of. Maybe you need to do another insert into another table right after the first insert, and
you need to use the prior ID for this purpose. This happens all the time in relational
databases. The function signature is like so:

$id = mysqli_insert_id( $connection );


This function returns the id of the most recently inserted record on the given connection.

How Do You MySQL Update With PHP?


Now that we completed some inserts using PHP and MySQL, we should take a look at
how to update records in the database. There are a few things to be aware of when doing
updates. Usually, you’ll want to complete updates by the record’s unique ID. When doing
an insert, we don’t need to worry about that since MySQL generates an ID automatically
with an auto increment function. In this example, we’re just going to look in the database
and choose the ID that we would like to update. In the real world, this ID will have been
generated on a different page. The other page will have used a SELECT to pull the record
out of the database, then it would be displayed on that page along with the ID of that
record. Now that ID may or may not be visible to the user on the page. Most likely, it is
transparent to the user, they wouldn’t even see it. Now there might be an ‘Edit This Entry’
type of link that would essentially pass along the ID via $_GET when you click that link.
There may also be a form which has a hidden field pre populated with the ID and get
passed via $_POST. The main idea however, is that one way or another, you are going to
need to provide that ID in order to update it! Let’s do it.
<?php
// 1
// open a connection
$dhost = 'localhost';
$duser = 'root';
$dpw = '';
$dname = 'bookmarks';
$connection = mysqli_connect($dhost, $duser, $dpw, $dname);

// test the connection


if(mysqli_connect_errno()){
die('Something went wrong with the database<br><br> '
. mysqli_connect_error() . ':'
. mysqli_connect_errno());
}

// 2
// define the query
// we'll pretend these are coming from a form via $_POST
// or from a link via $_GET
$url = 'http://google.com';
$name = 'The Google';

$query = "update links set name = '$name' where id = 11";

// run the query


$result = mysqli_query($connection, $query);

// test to see if the query was successful


if($result) {
// use mysqli_affected_rows to view how many (if any) rows were affected by the query
echo 'The Query Worked and there was '.mysqli_affected_rows($connection).' rows affected!<br>';
} else {
die('Look at this error - '. mysqli_error($connection));
}

// create a new query to view the records to oberve if the updates took
$query = 'select * from links';

// run the new query


$result = mysqli_query($connection, $query);

// while there are bookmarks, echo them out


while($bookmark = mysqli_fetch_assoc($result)){
echo $bookmark['name'].' lives at '.$bookmark['url'].'<br>';
}

// 5
// close the connection
if(mysqli_close($connection) == true) {
echo 'Database connection closed.';
}

?>

The Query Worked and there was 1 rows affected!


VegiBit lives at http://vegibit.com
Yahoo lives at http://yahoo.com
The Google lives at http://google.com
Database connection closed.

The query worked perfect and we can see that Google is now The Google and 1 row
Note!
was affected.

$count = mysqli_affected_rows( $connection );


That mysqli_affected_rows function is going to come in handy, and is often used with
update and delete statements in MySQL. The reason is, you may run an update query with
success, but no rows were affected in the database. What this means is that, yes you sent
a query, but there was nothing to change for that particular ID, so it did not affect the row.
To test this, we can run the query above multiple times and it is only the first time that 1
row gets affected. All subsequent queries that use the same query string are successful,
but no rows get affected. This is important to keep in mind.

How Do You MySQL Delete With PHP?


We now know how to Create “insert into table (column1, column2, column3…) values
(value1, value2, value3…)” records in MySQL with PHP, Read “select from table
where expression” records from MySQL with PHP, Update “update table set
column1=value1, column2=value2 where expression ” records in MySQL with PHP, and
now we’ll learn how to Delete “delete from table where expression” records in MySQL
using PHP. Create Read Update Delete. These are the four components of CRUD, and
with them, you are now free to rule the world. Let’s complete our training with the delete.
<?php
// 1
// open a connection
$dhost = 'localhost';
$duser = 'root';
$dpw = '';
$dname = 'bookmarks';
$connection = mysqli_connect($dhost, $duser, $dpw, $dname);
// test the connection
if(mysqli_connect_errno()){
die('Something went wrong with the database<br><br> '
. mysqli_connect_error() . ':'
. mysqli_connect_errno());
}

// 2
// define the query
// we'll pretend these are coming from a form via $_POST
// or from a link via $_GET
$url = 'http://google.com';
$name = 'The Google Homepage';

$query = "delete from links where id = 11";

// run the query


$result = mysqli_query($connection, $query);

// test to see if the query was successful


if($result) {
// use mysqli_affected_rows to view how many (if any) rows were affected by the query
echo 'The Query Worked and there was '.mysqli_affected_rows($connection).' rows affected!<br>';
} else {
die('Look at this error - '. mysqli_error($connection));
}

// create a new query to view the records to oberve if the updates took
$query = 'select * from links';

// run the new query


$result = mysqli_query($connection, $query);

// while there are bookmarks, echo them out


while($bookmark = mysqli_fetch_assoc($result)){
echo $bookmark['name'].' lives at '.$bookmark['url'].'<br>';
}

// 5
// close the connection
if(mysqli_close($connection) == true) {
echo 'Database connection closed.';
}

?>

The Query Worked and there was 1 rows affected!


VegiBit lives at http://vegibit.com
Yahoo lives at http://yahoo.com
Database connection closed.
Awesome!Note that the query worked perfectly and the entry associated with ID 11 is gone,
the bookmark link for Google.

Conclusion
We’ve come full circle covering the basics of PHP and MySQL manipulation. We can see
it’s a pretty straight forward process to implement CRUD with native PHP and MySQL.
Now, using any of the awesome PHP frameworks to handle these chores for you is
certainly an option. In cases where you might have a client that has hosting that might not
support the latest and greatest technologies however, you’ll need to know how to do these
things by hand in PHP. For those scenarios, this PHP Tutorial Series is the answer to your
woes.

Escape Strings For MySQL To Avoid SQL


Injection

With all the talk about working with databases using MySQL and PHP in this
tutorial series, one thing we didn’t cover yet is SQL Injection and how to protect
your site from it. The syntax for MySQL is very specific, and if you don’t get it
right, it is easy to break. As we build up queries using dynamic data from our
variables in PHP, you need to be careful that any data contained in those
variables do not break the syntax as well. One of the main things to look out for
is the single quote in strings. In this episode we’ll talk a little bit about SQL
Injection, and the method used to combat it.
What Is MySQL Injection
SQL Injection is the process of a malicious hacker on the internets that purposely tries to
take advantage of the specific nature of SQL syntax, and the fact that it can be broken. If a
hacker is able to carefully put together an URL string, form data, or cookie data, to
nefariously inject their malicious SQL into yours, your database could become the victim of
dropped tables, stolen data, entire databases being dropped, or worse. The main idea is
that the hacker takes advantage of the ability of single quotes to denote starting and
ending points of SQL code. If those single quotes are not properly escaped, then they are
prone to this type of attack.

The History of Escaping Strings


The problem of escaping strings goes all the way back to the beginnings of PHP. Recall
the main problem is that pesky single quote. There may be times when a string contains a
literal single quote that is needed, but we need to make sure that MySQL understands that
this particular single quote is not the end of string boundary, but an actual character that
we want in the string.
Problem
<?php

$status = "Hey buddy, you're on point today. Keep that stuff up.";

If we were inserting this into our database, it might look something like this:
insert into friends (status) values ( 'Hey buddy, you're on point today. Keep that stuff up.' );

The problem is that the single quote included in the string may cause a problem for
MySQL.
Solution
The solution to this problem is to simply escape the string like so.
insert into friends (status) values ( 'Hey buddy, you\'re on point today. Keep that stuff up.' );

What Does It Mean To Escape A String?


This is simply a means of telling MySQL that this is not the single quote that ends the
string, rather it is part of the actual string itself and should be treated as such. So as you
can see the way that we assign this special meaning to the character so that MySQL
knows it is safe, is to prepend it with a backslash character. PHP has had a few ways to try
and deal with this over the years, let’s look at a few now.
An Escaping Strings History Lesson
If you have a lot of data in your PHP application, you can see that having to escape any
single quote that may exist in the strings of your application by hand would be a tiresome
chore. Not only that, you’re bound to miss a few and introduce problems despite your best
efforts. Wouldn’t it be ideal to simply have a function that does this for you? Of course it
would, so PHP added this ability to the language many moons ago.

addslashes($string)
It all started with the addslashes function some time in the past. This function takes a
string as it’s argument, and returns the string with any problem characters like a single
quote automatically escaped for you. This was a good idea, so good in fact, that it was
made a default baked into the language by way of something called Magic Quotes.

Magic Quotes
Magic Quotes is a configuration directive in PHP that would automatically call addslashes
on all GET, POST, or COOKIE data by default. The thinking was that this would save
developers the mistake of forgetting to do this on their own and open up their websites to a
security vulnerability. This was added in PHP2 and became the default in PHP3. All good
things come to an end however, and in PHP5.4 Magic Quotes were sent to the trash can.
Why you say? Well, it caused a lot of confusion for developers, and made programs much
less portable from host to host. This is because one never knew if the configuration was on
or off for Magic Quotes. So in some cases, the code would work just fine, and in others if
might fail altogether. There is a solution to these woes however.

mysqli_real_escape_string( $connection , $string )


In the wonderful world of PHP, we sometimes run across insanely long function names
with underscores in between the words. This is one such instance. This is a great function
however which you should make use of. It takes a string and then escapes it in such a way
as to make it perfectly safe for MySQL statements. Therefore, you can build up your
queries in PHP as much as you like, then before you run the query, just make sure to put
the fully assembled sting through mysqli_real_escape_string and all will be well.
Observe
<?php
// 1
// open a connection
$dhost = 'localhost';
$duser = 'root';
$dpw = '';
$dname = 'bookmarks';
$connection = mysqli_connect($dhost, $duser, $dpw, $dname);

// test the connection


if(mysqli_connect_errno()){
die('Something went wrong with the database<br><br> '
. mysqli_connect_error() . ':'
. mysqli_connect_errno());
}

$query = "Isn't it nice that we don't have to escape ' characters all by ourselves?";

echo $query.'<br>';

$escaped = mysqli_real_escape_string($connection , $query);

echo $escaped.'<br>';

?>

Note that when the query is first echoed out, it contains all of those problematic ‘
characters. In MySQL, strings must be enclosed by single quotes exclusively, so by putting
this string inside of single quotes, the query is now broken and dangerous to the database.
Also notice that once we run our query string through the mysqli_real_escape_string
function, it comes out crisp, clean, and safely escaped for use with the database.

Provide The Correct Arguments


The mysqli_real_escape_string function takes two arguments. The first argument is the
database connection itself, and the second is the string you want to cleanse. It’s pretty
obvious that we need to provide the string to clean, but the database connection is not as
obvious. Just remember to provide it, or the function will in fact fail.

The mysqli_real_escape_string Conclusion


The takeaway from this quick lesson is, keep your data safe by properly using the
mysqli_real_escape_string function. When you’re using a framework, you won’t need to
worry about it, but when native PHP and MySQL is in use, you need to take care of this
step manually.

What Is Guzzle PHP?


You may have heard the term Guzzle come up lately in the PHP Community
and began to wonder what it is. We were curious as well so we decided to dig
into it a bit more. In this post we’ll take a look at what Guzzle is, what it is used
for, some of the projects that make use of it, and how you might be able to
make use of it as well. There will be a little bit of network speak and discussion
on web protocols, specifically HTTP, and how Guzzle works with it. Let’s jump
into learning about Guzzle now.

What Is Guzzle?
Guzzle is an HTTP client built with and for PHP. The cURL software has typically handled
all of the HTTP heavy lifting in PHP, or in some cases of quick hacking, the good old
file_get_contents() function. Guzzle is a bit more advanced and simple at the same time.
The software itself is quite impressive, providing a nice elegant solution to the developer
that is easy to use. All the complexity is hidden away in the class implementation.

How Do You Install Guzzle?


To install Guzzle PHP, you’ll want to make use of the best thing to happen to PHP ever,
The Great and Wonderful Composer. As we discussed many times here at VegiBit,
Composer is really advancing the art of PHP while encouraging developers to share code
like never before. So let’s go ahead and install Guzzle using Composer.
First up, let’s find the package on Packagist. To save you some typing, you can just click
this Packagist Link and be rewarded.
Create A Composer File With The Guzzle Requirement
Next, we need to create a composer.json file in the directory of our choice. For this
example, we’ll just go ahead and create a guzzle folder to hold our file. The composer.json
will look like this.
{
"require": {
"guzzlehttp/guzzle": "~5.0"
}
}

Run Composer Install


Now that we have a folder to hold the contents and a composer.json file constructed, we
can download the repository. Type composer install, and prosper.
C:wampwwwguzzle>composer install
Loading composer repositories with package information
Installing dependencies (including require-dev)
- Installing react/promise (v2.1.0)
Downloading: 100%

- Installing guzzlehttp/streams (3.0.0)


Downloading: 100%

- Installing guzzlehttp/ringphp (1.0.0)


Downloading: 100%

- Installing guzzlehttp/guzzle (5.0.1)


Downloading: 100%

Writing lock file


Generating autoload files

C:wampwwwguzzle>

Nice!If you made it this far, you now have a working copy of the Guzzle Software on you
local machine. Now you can test it out a bit.

What Is Guzzle For?


Guzzle allows your application to make HTTP requests. This begs the question, “What can
you make the request to?” Guzzle can make HTTP requests to any device that is capable
of sending an HTTP response, whether that be an API from twitter, facebook, or reddit, or
any public website. The official documentation uses http://httpbin.org/ for example calls, so
let’s test those out.
Create a Client and Make a Request
<?php

require 'vendor/autoload.php';

use GuzzleHttpClient;

$client = new Client();


$response = $client->get('http://httpbin.org/get');

echo '<pre>';
print_r($response);

?>

The output of the $response looks like this.


GuzzleHttpMessageResponse Object
(
[reasonPhrase:GuzzleHttpMessageResponse:private] => OK
[statusCode:GuzzleHttpMessageResponse:private] => 200
[effectiveUrl:GuzzleHttpMessageResponse:private] => http://httpbin.org/get
[headers:GuzzleHttpMessageAbstractMessage:private] => Array
(
[access-control-allow-credentials] => Array
(
[0] => true
)

[access-control-allow-origin] => Array


(
[0] => *
)

[content-type] => Array


(
[0] => application/json
)

[date] => Array


(
[0] => Wed, 22 Oct 2014 13:33:22 GMT
)

[server] => Array


(
[0] => gunicorn/18.0
)

[content-length] => Array


(
[0] => 275
)

[connection] => Array


(
[0] => keep-alive
)

[headerNames:GuzzleHttpMessageAbstractMessage:private] => Array


(
[access-control-allow-credentials] => Access-Control-Allow-Credentials
[access-control-allow-origin] => Access-Control-Allow-Origin
[content-type] => Content-Type
[date] => Date
[server] => Server
[content-length] => Content-Length
[connection] => Connection
)

[body:GuzzleHttpMessageAbstractMessage:private] => GuzzleHttpStreamStream Object


(
[stream:GuzzleHttpStreamStream:private] => Resource id #55
[size:GuzzleHttpStreamStream:private] =>
[seekable:GuzzleHttpStreamStream:private] => 1
[readable:GuzzleHttpStreamStream:private] => 1
[writable:GuzzleHttpStreamStream:private] => 1
[uri:GuzzleHttpStreamStream:private] => php://temp
[customMetadata:GuzzleHttpStreamStream:private] => Array
(
)

[protocolVersion:GuzzleHttpMessageAbstractMessage:private] => 1.1


)

Nice! We can see a ton of useful information about the response received right there.

Using A Guzzle Response


Just dumping the data out to the screen is not all that useful beyond learning and
debugging. Guzzle provides some methods you can use to work with the response.
<?php

require 'vendor/autoload.php';

use GuzzleHttpClient;

$client = new Client();


$response = $client->get('http://httpbin.org/get');

$statuscode = $response->getStatusCode();

$reasonphrase = $response->getReasonPhrase();
echo 'The get request to http://httpbin.org/get has a response with a statuscode of '.$statuscode.'
and a reasonphrase of '.$reasonphrase;

?>

The get request to http://httpbin.org/get has a response with a statuscode of 200


and a reasonphrase of OK

Accessing The Guzzle Response Body


Now that we know how to work with the HTTP status codes in our responses, let’s look at
how to parse the data in the response body. We can use the Guzzle getBody() method to
do this.
<?php

$body = $response->getBody();

echo $body;

?>

{
"args":{

},
"headers":{
"Connection":"close",
"Host":"httpbin.org",
"User-Agent":"Guzzle/5.0.1 curl/7.36.0 PHP/5.5.12",
"X-Request-Id":"6af65b26-cd0f-4822-b923-e14f66590ea0"
},
"origin":"204.79.197.200",
"url":"http://httpbin.org/get"
}

What Else Can Guzzle Do?


Guzzle can do a lot, and this is why you see so many popular projects in the PHP
community having Guzzle as a dependency. It really takes working with HTTP in PHP and
puts it on Steroids. In addition to the simple requests we did here as a proof of concept
type test, Guzzle can also manage json responses, fetch xml data, modify HTTP headers,
upload data, send post requests, maintain cookie sessions, and handle exceptions. Learn
all about Guzzle at the official docs.

What Is Goutte?
At the time of this writing, Laravel 5 development is in full swing – and there are
lots of changes coming down the pike. It would be fun to jump back in to
covering Laravel but things seem a little too fluid at the moment. We’ll know by
the end of the year where to focus our energies when working with Laravel
once the feature set and best practices are agreed upon and shipped. In the
meantime, let’s take a look at some of the various PHP repositories that might
be fun to tinker with. In this episode, we’ll take a look at Goutte which is written
by the legendary fabpot, or Fabien Potencier. Fabien is the creator of the well
known Symfony Framework which has components that are in use by many
projects in the PHP community.

The Components of Goutte


Goutte is a wrapper for the popular Guzzle package, combined with three other symfony
components. Those are Browser Kit, Css Selector, and the Dom Crawler. These are good
sources of documentation for using Goutte, since there really isn’t any for the Goutte
package itself. It will be a matter of simply installing, then kicking the tires to see what you
can find.

Installing Goutte
To your own copy of the package to play around with, head on over to Packagist to find the
requirements for your composer.json file. Oh heck, no need, here it is for you:
{
"name": "fabpot/goutte",
"type": "application",
"description": "A simple PHP Web Scraper",
"keywords": ["scraper"],
"homepage": "https://github.com/fabpot/Goutte",
"license": "MIT",
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
}
],
"require": {
"php": ">=5.4.0",
"symfony/browser-kit": "~2.1",
"symfony/css-selector": "~2.1",
"symfony/dom-crawler": "~2.1",
"guzzlehttp/guzzle": "4.*"
},
"autoload": {
"psr-0": { "Goutte": "." }
},
"extra": {
"branch-alias": {
"dev-master": "2.0-dev"
}
}
}

Start Testing Your New Goutte Install


With your new software installed and ready to go, let’s go ahead and see what we can do
with it.
<?php

// use composer to autoload Goutte


require 'vendor/autoload.php';

// get your namespaces right


use GoutteClient;

// create a new client, via Guzzle


$client = new Client();

// Check out the symfony.com subreddit and request the top posts from this month
$crawler = $client->request('GET', 'http://www.reddit.com/r/symfony/top/?sort=top&t=month');

// See if the response was ok


$status_code = $client->getResponse()->getStatus();
if($status_code==200){
echo '200 OK<br>';
}

// Use the symfony filter method to find all links which are children of paragraph
// elements which have a class of title then loop through the results using the each method

$crawler->filter('p.title > a')->each(function ($node) {


echo '<a target="blank" href="'.$node->attr('href').'" >'.htmlentities($node->text()).'</a><br>';
});

?>

200 OK
Introducing the Official Symfony Best Practices
New in Symfony 2.6: Bootstrap form theme
New in Symfony 2.6: AJAX requests in the web debug toolbar
New in Symfony 2.6: Farewell to ICU component (Symfony Blog)
New in Symfony 2.6: LockHandler
Symfony 2.5.5 released
New in Symfony 2.6: Date support for Validator constraints
Commerce Guys makes big investment in Symfony, for eCommerce and Platform.sh
Symfony, 9 years of history, rewards its top 150 contributors
Let’s revive Symfony Montreal meetups!
New in Symfony 2.6: Smarter assets:install command
Symfony 2.6 fast approaching its stabilization phase
New in Symfony 2.6: New shortcut methods for controllers
A week of symfony #406 (06-&gt;12 October 2014)
Tell Doctrine to use a different database user when using the symfony console?
Symfony 2.4.10 released
A week of symfony #407 (13-&gt;19 October 2014)
Awesome!With the Goutte software we were able to fetch all the links from the Symfony
subreddit.
Goutte vs SimpleHtmlDom
Simple HTML Dom is another handy piece of software for doing tricks like this. It is a bit
easier to use than Goutte, however if you learn all the details of how Goutte works, it may
help with your Symfony chops. In dealing with Laravel, which relies on several Symfony
dependencies in order to work, many have become more interested in what Symfony has
to offer.

Symfony Dom Crawler


Let’s look a little bit more at the script above. When we ran $client->request(), a var
dump of the $crawler variable gives us object(SymfonyComponentDomCrawlerCrawler).
There are three classes in the SymfonyComponentDomCrawler namespace. You have
the Crawler class itself, which helps to navigate a list of Dom Elements.
The Form and Link classes allow you to programmatically interact with forms and links on
a webpage via PHP. It’s almost like creating a virtual web broswer via PHP, which is really
kind of cool. To see all the options available, visit the API.

Log In To A Website With Goutte


Now you may be saying, yeah yeah yeah, we can do all of this in native PHP. To be fair,
sure, you can. Get a load of this however. We can also log in to websites and navigate as
a logged in user using Goutte. We got a little mind blowing stuff happening coming up,
check this out.
<?php

// use composer to autoload Goutte


require 'vendor/autoload.php';

// get your namespaces right


use GoutteClient;

// create a new client, via Guzzle


$client = new Client();

$crawler = $client->request('GET', 'https://github.com/login');

// select the form and fill in some values


$form = $crawler->selectButton('Sign in')->form();
$form['login'] = 'your user name';
$form['password'] = 'your password';

// submit that form


$crawler = $client->submit($form);

// we are now logged in and can navigate the site


// Click the Explore Link
$link = $crawler->selectLink('Explore')->link();
$crawler = $client->click($link);

// Click the Front End Javascript Frameworks link


$link = $crawler->selectLink('Front-end JavaScript frameworks')->link();
$crawler = $client->click($link);

// get the a elements that are children of h3 elements


// the repository names are here
$crawler->filter('h3 > a')->each(function ($node) {
echo '<b>'.$node->text().'</b><br>';
});

?>

angular/angular.js
jashkenas/backbone
emberjs/ember.js
knockout/knockout
tastejs/todomvc
spine/spine
Polymer/polymer
mozbrick/brick
facebook/react
Try it out for yourself! You can try your credentials as well on your own setup and see
Epic!
how to navigate the site via PHP. We’re not sure what the use case for this would be, but
nonetheless, it’s pretty impressive and a testament to the power of the software.

Conclusion
In this episode, we took a look at Goutte, the powerful combination of Guzzle and Symfony
Components such as Browser Kit, Css Selector, and Dom Crawler. It’s fun to play around
with these tools for learning purposes, and no doubt forces you to dig into the structure of
the DOM, which is sometimes a little tricky.

Combine PHP Functions To Make Your


Own

One of the great things about PHP is the fact that it has built in functions for
anything and everything. A really neat thing to do is to try to stitch these
functions together to create interesting new functions. If there are functions in
PHP that you really like and want to extend them so to speak, you can do this
by creating your own. In this episode, we’ll take a look at doing just that. We’ll
have a look at preg_match_all, array_count_values, and arsort, to create a
new and awesome function named preg_count_sort. Let’s check it out.

The Native Functions


First off, we’ll take a quick look at the native PHP functions we’ll test out here.
preg_match_all
This function accepts a regular expression pattern, a subject to match against, and the
name of a variable which will hold an array of matches.

array_count_values
This function takes an array as input, then counts the number of times each value happens
in the provided array. It then creates a new array, with the keys of the new array being the
original values, and the values now containing a count of how many times the original
value appeared in the original array.

arsort
There are a tremendous amount of array functions in PHP so you can find whatever you
need for sorting. This one sorts the provided array in reverse order and keeps the original
keys in tact, which we need for our little application here.

The Function of Functions


Now we’ll take a look at how to combine the three functions we mentioned here into one
cool function of our own. We’re going to call it, the preg_count_sort function.

preg_count_sort
Here is the source code for the function.
function preg_count_sort( $pattern, $subject ) {

echo '<table class="table table-hover">';

preg_match_all('/'.$pattern.'/', $subject, $matches);

$result = array_count_values($matches[0]);

arsort($result);

foreach($result as $match => $count){


echo '<tr><td>'.$match.'</td><td width="50%" align="right">'.$count.'</td></tr>';
}
echo '</table>';
}

Let’s talk about how it works. First off, we simply define the function by using
the function keyword followed by the name of the function we wish to declare. Note that
this function takes a pattern, which will be a regular expression, and a subject, which will
be the data against which the regular expression will run. Next up, we open up a table tag
since we are going to put the results of our function into a nice tabular output. On the next
line we make use of the first of the original PHP functions, preg_match_all. This function
takes the regular expression pattern as the first parameter, the subject to match against as
the second, and the name of the array to hold any matches as the third. Note that we
include the starting and ending delimiters for the pattern by including the forward slash at
the beginning and end of the pattern. This way, when we provide the regular expression in
our application, we don’t have to also provide the beginning and ending
delimiters. array_count_values is the second native php function to make use of. This
counts the number of times each match occurred in the matches array which the
preg_match_all function populated. Once we have the count of matches, we use the third
native PHP function arsort, to sort the counts from highest to lowest in number. The
foreach loop simply loops through all the matches placing them into rows and cells within
the overall table. Lastly, we just go ahead and close out the table tag.

Put The New Function To Use


We’ll put this code to use in a little single page application and test it out. Let’s see it now.
preg_count_sort.php source
<html>
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/respond.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body class="container">

<?php

$subject = isset($_POST['subject']) ? ($_POST['subject']) : '';


$pattern = isset($_POST['pattern']) ? ($_POST['pattern']) : '';

if( strlen($pattern) > 0 ){


preg_count_sort( $pattern, $subject );
}

function preg_count_sort( $pattern, $subject ) {


echo '<table class="table table-hover">';
preg_match_all('/'.$pattern.'/', $subject, $matches);
$result = array_count_values($matches[0]);
arsort($result);
foreach($result as $match => $count){
echo '<tr><td>'.$match.'</td><td width="50%" align="right">'.$count.'</td></tr>';
}
echo '</table>';
}

?>

<br>
<strong>Subject</strong><br>
<form action="preg_count_sort.php" method="post">
<textarea type="text" name="subject" cols="100" rows="5"><?php if(isset($subject))echo
htmlentities($subject); ?>
</textarea>
<br>
<strong>regular expression pattern</strong><br>
<input name="pattern" type="text" size="100" value="<?php if($pattern) echo $_POST['pattern']; ?>">
<br>
<br>
<button type="submit">Preg Count Sort</button>
</form>
</body>
</html>

So what does this little app do for us? Well, we can test it out. Let’s define our Subject and
pattern, then run the program.
Our subject will be this text string: “If you like apple products, you might have an iPad,
iPhone, or even an iMac. If the macbook pro is not your thing, you might like the Lenovo
Carbon X1. The latest generation iMac is fantastic, however the decade old iMac sitting on
my desk is more of a collectors item at this point. No need of a new iPad yet, the original
retina display version still works just fine.”
Our pattern will be this expression: i[A-Z][a-z]*
Here is the result when we run the program

When we ran the function, we found that in the subject iMac occured 3 times,
Pretty Cool!
iPad occurred twice, and iPhone occurred once. Of course this is a bit of a nonsense
example, however if you brush up on your regular expressions and provide a lengthy
meaningful subject, you can uncover all kinds of interesting data.
Conclusion
This quick episode took a look at combining PHP functions together to create your own. If
you use your imagination, you can take this approach with any number of functions which
accept and output data to create your own custom made solutions.

Learning About Regular Expressions

Most likely you have come across Regular Expressions at some point during
your software development. Regular expressions are one of those things that
tend to make people take sides and form strong opinions. Some swear by their
use, while others have a deep disdain for them. Either way, they are a
necessary evil – we need to learn about them in order to round out our skills so
to speak. In this episode, we’ll take a quick look at some of the basics in getting
up and running with regular expressions. We’ll also build a fun one page PHP
application to test our own regular expressions with. Let’s jump right in.

Matching Literal Text


The easiest type of regular expression is by matching things with literal characters. Of
course since it is the easiest, it is also the least powerful and useful. It does get us going
however with how these things work, so let’s take a look. Here is our first regular
expression:
/yaba daba/
There are a few things to note here. First, you’ll notice that at the beginning and end of the
pattern are forward slashes. These are needed to signify the beginning and end of the
pattern. When you have a pattern, you need a subject to match against. Let’s create an
example sentence of, “I have no idea why I chose yaba daba in the regular expression
pattern” Our regular expression will match the string “yaba daba” in the subject, and
nothing else. The pattern /Yaba Daba/ would not match at all, due to case sensitivity.

Metacharacters
At this point its good to mention the special characters in regular expressions. Here is a
table of them.

Metacharacter Meaning

this is the escape character used for several things

^ refers to the start of the string

$ refers to the end of the string

. powerful match any character except newlines

[ begin a character class

] end a character class

| the pipe is for alternation – basically an ‘or’

( start a capture group

) end a capture group

? several uses – mostly with capture groups

* match zero or more

+ match 1 or more

{ begin a number range match

} end begin a number range match

We have a nice little overview of what all these characters do. Fear not, if they
Fantastic.
mean nothing right now, they will make more sense as we move on.
Since these characters above have special meaning, if you are trying to match them in a
string, you must escape the character in your regular expression. Consider the string Do
you know what 2 + 2 is equal to? {we will soon find out} [haha]. If we apply the regular
expression /2 + 2/ it fails. If we try /2 + 2/ it now works. Again, this is because the plus
sign is a special character so it must be escaped with the backslash character. What if we
need to match that text in between the curly braces? You might think that /{[a-z ]*}/ but
it does not, we must again escape the special characters like so /{[a-z ]*}/ and now it
works.

Character Classes In Regular Expressions


This makes a nice segway into character classes, in fact that very last regular expression
we used contained a character class. We can start by reviewing the prior example to see
how it works. In fact, we’ll make use of an incredible online tool over at regexr. What’s
really cool about regexr is that when you paste in your regular expression, you can hover
over each character for it’s meaning which is really slick. Let’s examine the prior example.
/{[a-z ]*}/
Within this pattern is a character class, it is this piece of the pattern: [a-z ] By hovering
over each character at regexr we can find the meaning. So in order, [ opens the character
set, a-z says to match any lowercase character in the alphabet, then we have a space
character, then the ] closes the character set. Here is what it looks like at regexr.

The best thing to do is to simply paste in various subjects and patterns and have a
Slick!
play for yourself. If you need all the nitty gritty on character classes head right here.

Digits, Word Characters, and Whitespace Characters


There are some convenient shorthand character classes for digits, word characters, and
whitespace characters. These are handled by d, w, and s respectively. Easily see these in
action right here.
Regular Expression Alternation
As ever, a simple concept is given a fancy term. As your mind explodes from the myriad of
technical terms and acronyms from working in high tech, regular expression jargon
continues to deliver this idea with alternation. What is alternation? Choose this or that.
Done. Next lesson.
A bit tongue in cheek of course, but the idea is simple. It works much like the logic you
might find in an if statement when programming where you say if this condition or that
condition, or that condition, and so on. For example, continuing with the simple string of
text we’ve been working with so far, we will apply a pattern that includes alternation in it.
Here is the pattern /(to|we|ha)/ and it simply means to match to or we or ha in the
subject. Regexr shows us this result.
Awesome! Prior to regexr one had to make use of something like RegEx Buddy, which while
it is a great piece of software, it is not online, and it is not free.
Thanks http://gskinner.com/ for making this free tool for all of us to use! Here is what the
PHP manual has to say about alternation.

The Dot Character and the Asterisk Character


The de facto bazooka of regular expressions comes in the form of this simple combination.
The dot followed by the asterisk, or .* Look at how unassuming that little combination of
two characters is. Just a simple dot and asterisk. What this means however, is to match
anything, any number of times. It can be used in certain situations, but most teachings will
advise to use this combination only as a last resort. In fact, if we plug this pattern into
regexr, it gives us an infinite warning.

Of course like a good hacker, this is the only pattern of regex I use when hacking in a
playground environment, but seriously folks, careful with the big guns.

Greed is Good
Greed is good, or so said some nutjob on wall street many moons ago. Speaking of wall
street, did you see that movie with that dude from the Titanic? Great flick, those guys were
crazy. Anyhoo… In regular expression we have this concept of greediness. What it means
when something is greedy in the regex sense, is that it will try the match as many times as
it possibly can before it stops matching. If there is anything that can trip you up when
working with regular expressions, it is definitely greediness vs laziness. When is a
particular token greedy? When is it lazy? How does this affect the pattern I am trying to
use? You’ll need to take all of these things into consideration when building your own
patterns. Beyond rote memorization, which does have it’s merits, it is usually a matter of
visiting a tool like regexr and simply testing out the various quantifiers to see what works.
Let’s see an example of greediness in action. We’ll make use of this pattern /w/ which be
reminded is a word character and is greedy. This is the result on our test string, note that it
matches every single word character in the string.

Turn Down for What?


How can we turn off that greediness? Simply add the question mark character like
so /w?/ and see the result.

Lookaheads and Lookbehinds


So far we have but only scratched the surface of regular expressions. If you’re new to
them, you’re head is probably spinning. If you’re already familiar with them, this episode is
nothing more than a refresher for you. In any event, we can now take a look at a regex
favorite, the ability to look ahead or behind of the pattern match to determine the delimiters
so to speak of what characters we will capture. These delimiters are just that, they are not
included in the actual match. Let’s check out how these guys work.
Positive Lookahead
First up, we’ll take a look at the positive lookahead. This tells the pattern to look ahead, or
look after the pattern for a specific pattern, and only match if that secondary pattern exists
after the main pattern. It sounds strange, so lets just look at how this works. First, lets find
any sequence of 3 word characters like so.

Ok, pretty neat. You can see we find any sequence of 3 characters in a row and it works
pretty well. Now, lets change it up. Lets find three characters *only* if they are followed by
a curly brace like this }. How can we do such a thing? We can do it with the positive
lookahead just like this.

You see that partner? Very cool – a match is found and the delimiter, or the specified
character of the positive lookahead, is not contained in the match. This is immensely
useful! Once again, (?=) is the syntax for a positive lookahead.

Positive Lookbehind
We can do the same thing for matching patterns in instances where we would like to look
*before* the main pattern for a specific piece of text or a specific character. This is the
positive lookbehind. We’ll modify our regex to match only 2 word characters in a
row *only* if they are preceded by a curly brace like this {. This can be accomplished with
the pattern of (?<={)[a-z]{2} which will match we in the string Do you know what 1 + 1 is
equal to? {we will soon find out} [haha]. Note that (?<=) is the syntax for the positive
lookbehind.
Negative Lookahead
The inverse of the positive lookahead and lookbehind are the negative lookahead and
lookbehind. These are the exact opposite of the prior examples. Basically, only match the
given pattern if it is *not* followed by or preceded by a given character or string. For
example, if we want to find all groups of 3 characters *only* if they are not followed by a
curly brace like this }, we can do that.

Ah, yes. Look at that. Ain't she a thing of beauty? All of those nice three character
combinations, but wait, look at that out right before the curly brace. It is not highlighted as
a match. Yes that's right, that's due to the negative lookahead. Note that the syntax for the
negative lookahead is (?!) where the thing that you do not want to match comes after the
exclamation point.

Negative Lookbehind
Just like we have a negative lookahead, we have a negative lookbehind, and the syntax for
this is (?<!) where the thing that you do not want to match comes after the exclamation
point.

Additional Regular Expression Learning Resources


• https://www.regex101.com/
• http://regexone.com/
• http://www.regular-expressions.info/tutorial.html
• http://regex.learncodethehardway.org/book/
• http://www.regexr.com/
• http://qntm.org/files/re/re.html
• http://www.rexegg.com/
• http://www.codeproject.com/Articles/9099/The-Minute-Regex-Tutorial

Conclusion
Regular expressions are dry stuff folks, much like the Mojave. In fact, the more outlandish
the writing, the more boring the topic being covered. At about 1900 words, that's just about
all I can muster for regular expressions today. I think we covered some good starting
points for regular expressions in this episode. They may be a bit dry, but they are
immensely powerful, and when you need them, they just might be the only way to solve a
difficult string or character related problem. Tune in again when we build our very own
regular expression application in our very next episode!

Build Your Own PCRE Regex Tester With


PHP

As promised, in this episode we will build our very own regular expression
tester so we can test out various regex patterns. As we covered in the prior post
on regular expressions, there are many great tools to do this online as well. So
what is the reason to build our own? It’s simple really, it’s fun to do and a great
learning exercise too. What we’ll set out to do is build a simple one page
application that accepts a string of data, or subject, as well as a pattern. We’ll
then have a submit button that will run the pattern against the subject using
the preg_match_all function build into PHP. Let’s check it out.

Create The Form


First up, we need the form to accept the data we want to test.
<form action="preg_match_all.php" method="post">
<textarea type="text" name="subject" cols="100" rows="5"><?php if (isset($subject)) echo
htmlentities($subject); ?>
</textarea>
<br>
<strong>regular expression pattern</strong><br>
<input name="pattern" type="text" size="100" value="<?php if ($pattern) echo $_POST['pattern'];
?>">
<br>
<br>
<button type="submit">Preg Match All</button>
</form>

So in this snippet there are a few things to note. We’re simply going to post the form
to preg_match_all.php which is the name of the one file in this application. We include a bit
of code to check for the presence of data that may have been submitted via the form. If it
has, we repopulate the form with those values. This way, we don’t have to continually
paste back in the data that we’re testing against for the subject. This also helps for the
pattern since we can make incremental edits to the pattern easily and continue to test
against the subject in question. Finally we include a simple submit button, which we’ve
addressed with the text, “Preg Match All”. It looks like this.

Cool. We can see there is a text area to input some data that we want to check against, a
text input for the regular expression pattern, and a simple submit button.

The Form Processing Script


Here is the snippet of PHP that will handle the form processing when it is submitted. This
actually goes *above* the html for the form so that we can capture form data for
repopulation if needed.
<?php

$subject = isset($_POST['subject']) ? ($_POST['subject']) : '';


$pattern = isset($_POST['pattern']) ? ($_POST['pattern']) : '';

if (strlen($pattern) > 0) {
preg_match_all('/' . $pattern . '/', $subject, $matches);
foreach ($matches[0] as $match) {
echo $match . '<br>';
}
}

?>
First, we use the ternary operator to check for data submitted via the form. If there
Excellent.
has been no data submitted, we simply enter an empty string into the $subject and
$pattern variables.
Next up, we use a simple if statement to check the length of the $pattern using
the strlen function. If the $pattern has a length that is greater than zero, then we proceed
to run the preg_match_all function using the data that had been submitted from the
form. preg_match_all is a fantastic function you can use to check for all matches within a
subject. The first parameter to this function is the actual pattern to use for the regex. Note
that in the code above, we added the delimiters ahead of time, that way when we enter the
pattern in the form we don’t need to include them. This is just a simple convenience
mechanism. The second parameter is the subject that we will test the regular expression
against. This is the data that comes in from the textarea in our form. The third parameter is
named variable to hold the matches that result from the regular expression being run.
With preg_match_all, the matches actually get stored in a multi dimensional array. This is
why when we loop over this array, we loop over $matches[0] and not $matches. Finally, we
simply echo out each match followed by a line break. The entire script looks like this.
<html>
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

<body class="container">

<?php

$subject = isset($_POST['subject']) ? ($_POST['subject']) : '';


$pattern = isset($_POST['pattern']) ? ($_POST['pattern']) : '';

if (strlen($pattern) > 0) {
preg_match_all('/' . $pattern . '/', $subject, $matches);
foreach ($matches[0] as $match) {
echo $match . '<br>';
}
}

?>

<br>
<strong>Subject</strong><br>

<form action="preg_match_all.php" method="post">


<textarea type="text" name="subject" cols="87" rows="5"><?php if (isset($subject)) echo
htmlentities($subject); ?>
</textarea>
<br>
<strong>regular expression pattern</strong><br>
<input name="pattern" type="text" size="89" value="<?php if ($pattern) echo $_POST['pattern'];
?>">
<br>
<br>
<button type="submit">Preg Match All</button>
</form>
</body>
</html>

This is super simple and basic, but it should make for a nice quick and dirty testing tool for
some of our regular expressions. Let’s examine positive and negative lookbehinds. Recall
from our prior post that this is when the regular expression looks behind, or before, the
pattern in question. This is good for matching something that only is preceded by a
particular character or string of characters. Here is a screenshot or our tool completing a
successful positive look behind match.

This is right after the submit button had been clicked. We can see the match of ‘we’ gets
output at the very top, and our form is populated with the data we had used. This way we
can easily edit the data in the form, and try another test. This used Do you know what 1 +
1 is equal to? {we will soon find out} [haha]. for the subject and our regex pattern
was (?<={)[a-z]{2}. This pattern says, match any two characters within the range of lower
case a to z, *only* if it is preceded by a left curly brace. Nice!
Let's now test the negative lookbehind. We can modify the pattern to (?<![)[a-z]{4}which
says to match any four sequential characters as long as there is not a left bracket before
them. We can see here that this works, as the string 'haha' was not matched, but several
other consecutive four characters were.

Conclusion
Should you now ever find yourself without an internet connection and unable to reach any
of the fine resources we covered in the last episode to test your regular expressions, you
now have a really simple way to test them locally if need be. It's quick, dirty, and useful -
perfect if you ask me

Php Tutorials For Beginners


Let’s jump into some Php Tutorials For Beginners! PHP is the most widely used
programming language on servers that power websites for the Internet. It is a
scripting language, yet quite powerful with thousands upon thousands of built in
functions. PHP is a fantastic alternative to other languages like active server
pages, Java, or Ruby. When you’re first starting out with the language, it can
seem a bit overwhelming to know where to begin. This great collection of php
tutorials will get you going in the right direction when you’re first starting out.
• http://vegibit.com/php

This Php tutorial series covers the gamut and if


you take the time to go through the entire series, you’ll be able to build simple
dynamic websites by the time you finish. Learn about variables, data types, useful
functions, flow control, HTTP handling, database interaction, and more!

• http://php.net/-manual/en/tutorial.php

If you’re going to learn PHP, you might as well


go right to the source, that is the official PHP documentation website. This particular
tutorial is a perfect first step for the PHP beginner. In it, you’ll learn what you need to
run PHP, creating your first PHP powered page, working with forms, and more.

• http://php.about.com-/od/learnphp/ss/phpbasics.htm
The beginners guide to programming in PHP
found at about is a very solid introduction to the language, how it is used, and how
you can learn it quickly. This 9 part series is perfect for the beginner learning PHP.

• http://w3schools.com/-php/

Always a good resource for things web


development related, W3 schools has some nice approaches to learning where you
can “try it for yourself” or “run an example”. Despite more seasoned developers
considering w3 schools a second rate site, they do serve a good purpose for
beginner level skills.

• http://tutorials-point.com/php/
Tutorials point is a great site with the motto of,
“Simply Easy Learning.” They take this approach to explain the nature of working
with PHP as a beginner to get up to speed and build you base with PHP.

• http://code.tutsplus.com/-tutorials/the-best-way-to-learn-php–net-22287

The tutsplus brand from the fine folks at envato


always create some first class content for learning just about anything you want. This
article on the best way to learn PHP is no different. They also make a nice reference
to the haters of PHP, and its best to disregard them.

• http://codeproject.com/-Articles/759094/Step-by-Step-PHP-Tutorials-for-Beginners-Creating
Codeproject is another high quality site to help
with your adventures in PHP. This article take you through creating a new program
from scratch, with authentication, membership roles, and create read update delete
functions.

• http://lynda.com/-PHP-training-tutorials/282-0.html

In other breaking news, Lynda has just been


sold to LinkedIn for 1.5 billion dollars. Way to go Lynda! In addition to their business
prowess, Lynda provides some excellent resources for aspiring developers. They
make note that indeed a full 80% of websites on the internet today make use of PHP.
Lynda is a great resource for you to add to your learning.

• http://codecademy.com/-tracks/php
Codecademy once again makes the list as they
are one of the best ways to learn with hands on exercises right in the browser. They’ll
teach you to program in PHP the widespread programming language that is
everywhere, even on huge sites like Facebook.

• http://speckyboy.com/-php-tutorials-for-beginners/

SpeckyBoy is a solid website that provides


some great tutorials for all aspects of web development. They note that PHP is
easier to learn than languages like Java or .NET, so it makes a good starting point
for beginners. If you’re a programming or PHP noob, this article is a good one for
you.

• http://devzone.zend.com/-php-101-php-for-the-absolute-beginner/
Zend has done more for PHP than anyone else.
They provide a dedicated Zend server, Zend Studio, and professional level
enterprise PHP training. Thankfully, they also provide a fantastic series titled PHP
For The Absolute Beginner. This is another fantastic resource to add to our list.

• http://w3resource.com/-php/php-home.php

The series at w3resource will take you through


installation, basic variable types, data types, constants, operators, control
statements, object oriented programming, forms, cookies, and more. The exercises
are mostly geared towards the beginner.

• http://webmonkey.com/-php_tutorial_for_beginners/
Webmonkey is another oldie but goodie from
the fine folks over at Wired Magazine. Webmonkey notes that although simple, PHP
is powerful and fits in perfectly with the even more basic language of the web, HTMl.
Webmonkey’s PHP Tutorial For Beginners is a perfect addition to your collection.

• https://css-tricks.com/-php-for-beginners-building-your-first-simple-cms/

You would think a site that is called css tricks


would be strictly front end only, but alas, that is not the case! Css tricks is one of the
best web development sites on the internet, and as such they cover all kinds of
topics, not just CSS. In this beginner level PHP tutorial, you’ll learn how to create a
database, connect to a database, display a form, save form data to a database, and
more.

• https://www.codeofa-ninja.com/-php-and-mysql-crud-tutorial.html
Finally, we have the code of ninja – because
who doesn’t want to be a Ninja?! In this article, you’ll learn everything a beginner
needs to know to get up to speed with PHP.

Php Tutorials For Beginners Summary


That should be enough content to keep you going for some time at the beginner level. If
you have the time and patience to go through all of them, you surely won’t be a beginner
for too long.

Learn PHP and Programming by using the


Eclipse PDT Debugger
When you’re starting out with programming and reading tutorials as well as
watching screencasts, it is sometimes hard to grasp what the code you are
learning about is actually doing. Wouldn’t it be great to be able to go through
the code step by step and watch the status of variables update in real time,
cycle by cycle. Once you learn how to do this, you will be cooking with gas and
ready to improve your knowledge radically.
We’re going to cover how to do this right now, it’s fun and easy! You’ll start by getting the
Eclipse PDT all in one package by visiting the Zend website
here http://www.zend.com/en/company/community/pdt/downloads and choosing your
platform. In this case we’ll choose Windows.

Go ahead and download the package, unzip the contents and launch your Eclipse PDT
software. Once you have downloaded and installed your software, you still have to install
and configure a debugger in the IDE. There are a few ways to do this and it can be
frustrating the first time you attempt it, but outlined here is the easiest method to install the
debugger and get ready to step through some code. First you will navigate to
Window->Preferences->Install/Update->Available Software Sites.
Once there you will need to click Add, then put in the details as follows:
Name: PDT
Location: http://downloads.zend.com/pdt
Now you will navigate to Help->Install New Software and choose your newly added
download location from the dropdown menu, then choose the Zend Debugger Feature, hit
next and follow the prompts. Restart the IDE when asked.

We’re almost there and ready to start debugging and learning some snippets of code but
first we need to configure our debug configurations. First create a new PHP project named
‘test’ by way of File->New->Local PHP Project and create a simple index.php file in the
project. Once you have done this add the following code snippet to your index.php file.
<?php
echo '<pre>';
$vegibit = array(
"learn" => "PHP",
"read" => "vegibit.com",
);

print_r($vegibit);
?>
Let’s now configure our debugger by choosing Run->Debug Configurations. In this window
you will choose PHP Script as a CLI Application, Alternate PHP for your installed PHPs
and browse for the index.php file you just created in your project named ‘test’. In the name
field we’ll simply call this instance of the debugger ‘debug it!’. Apply all settings once
complete. Here is a screenshot of the settings.

Ok friends, let’s get debugging! Now that we have our project created, our debugger
installed and configured, as well as the snippet of code provided saved in our index.php
file, we can launch the debugger. There are several ways to do this in the IDE but we’ll
choose the bug icon in the toolbar to launch this one. You will then be prompted for a PHP
to Debug Perspective Switch, choose Yes.
This is where the fun starts as your code launches and stops at the very first line. We can
now step into each and every line of code to debug exactly what it is doing. This gives us
incredible insight into how our code works rather than the constant placement of print_r
and var_dump statements in our PHP files. Below is what the IDE will look like as the code
executes and stops at line 2. The IDE shows you all of the environment variables, console,
and browser output, among many others.

Now click on the Step Into icon or F5 key two times slowly to watch a pre tag get echoed
out for nice formatting, as well as see an array named $vegibit get created with the keys of
learn and read as well as the values of PHP and Vegibit.com. Observe your newly created
variable in the variables window in memory before these values are even sent to the
screen! Pretty slick!
Finally click on Step Into one more time and finish the execution of the script to view the
final output.

Now you have a debug environment that you can use to debug any snippet of PHP code
you like. A great way to learn is to simply go to php.net and copy one of the many samples
of code into your index.php file of your test project, save, and debug it the very same way
we just did here. You can now step through any piece of code you can find and learn
exactly what it does line by line in real time! Fun stuff indeed.

What Are PHP Arrays?


Arrays are common not only in PHP, but in any programming language you will
come across. Arrays are very useful since they allow us to group together
information in a very organized way. At it’s core, an array is a collection of
different pieces of information or data which is ordered and indexed via
integers. The information gets stored in specific index positions which makes it
convenient to insert into and remove out of each pocket or index so to speak.
An array can hold pretty much whatever you want to put into it, whether that is a
string, number, integer, floating point values, another array, or an object. We’ll
be using arrays more and more moving forward so let’s dig right into the nitty
gritty with PHP Arrays now!

Creating an Array in PHP


With those beginning thoughts in mind concerning arrays, let’s create one and put some
information in it. In this example, let’s imagine we want to have just one variable that
contains a collection of house styles. We can do this by creating an array, populating said
array with the styles we want, then assigning that array to the variable. This is how we
might do this:
<?php

$houses = array('Colonial', 'Contemporary', 'Southwestern', 'Metro');

?>

Just like that we have an array which is now stored in the $houses variable. Great, so how
do we get information out of our array now? Well, lets try to echo out the information in that
array like we have been doing with all of the other variable types up until now.
<?php
echo $houses;
?>

Notice: Array to string conversion in C:wampwwwphpconsoleindex.php(61) :


eval()’d code on line 3
Array
Hmm. Not great. When we tried to echo out the information in our variable, it gave us a
warning. It did tell us however that the variable contains an array. There is a different
notation for working with arrays when we’d like to retrieve information out of them. We
need to specify the index we are interested in using the square brackets notation like
so []. You’ll need to keep in mind that arrays are zero based. That means with arrays you
don’t begin counting from 1, you count starting at 0. So in our example we populated our
array with f different styles of houses. This means we need to look in index [0], [1], [2],
and [3]. Notice how we use the square brackets to enclose the index we want to get
access to. Let’s try it out in our testing ground:
<?php

$houses = array('Colonial', 'Contemporary', 'Southwestern', 'Metro');

echo $houses[0].'<br>';
echo $houses[1].'<br>';
echo $houses[2].'<br>';
echo $houses[3].'<br>';
?>

Colonial
Contemporary
Southwestern
Metro
Now we’re seeing how to grab the info out of the variable. So at index zero we have
Nice!
our Colonial, index 1 has a Contemporary, index 2 Southwestern, and index 3 has a Metro.
With arrays you can store as many values as you need to, maybe you have 500 emails
you want to store in a variable, with an array you can do that no problem.

Mixed Values in Arrays


When you have an array, you are not limited to the types that you can store in it. Just
above we put a handful of strings into the $houses variable. Now, we can set up variable
that is a bit more dynamic. Let’s see how.
<?php

$dynamic = array(7, 'House', 'Car', array('grass', 'mower', 'mulch'));

echo $dynamic[0].'<br>';
echo $dynamic[1].'<br>';
echo $dynamic[2].'<br>';

?>

7
House
Car
First, we assigned a bunch of values to our new dynamic array. At index 0 we
Excellent.
placed a number in, specifically an integer. At index 1 is a string. Index 2 is also a string.
Note that in the third index is an array. Well how about that America, an array within an
array. Yes You Can! Consider this an introduction to multi-dimensional arrays. Having an
array within an array requires us to put on our thinking cap. We saw how to get at the data
contained in simple array, now how do we deal with this type of thing. Let’s see.
<?php

$dynamic = array(7, 'House', 'Car', array('grass', 'mower', 'mulch'));

echo $dynamic[0].'<br>';
echo $dynamic[1].'<br>';
echo $dynamic[2].'<br>';

echo '<br>';

echo $dynamic[3][0].'<br>';
echo $dynamic[3][1].'<br>';
echo $dynamic[3][2].'<br>';
?>

7
House
Car
grass
mower
mulch
When there is an array within an array, you need to level up partner. That is, you
Fantastic!
need to get to the next level. Notice how we use the double bracket notation to dig deeper
into that array within an array [][]. What is this doing for us? Well you see, in the first
bracket, we need to specify where we want to look. In this case we want to look at position
3 since that is where the second array lives which we want to peer into. Ok, great – now
just repeat the process. Now that you’ve specified the third position of the first array, what
position of the second array do you want to access? Put this value in the second bracket.
This is how you access arrays inside of arrays and this is what you call a multi dimensional
array. You are not limited to only two levels either. You can have arrays within arrays
within arrays, however you will begin to drive yourself mad if you nest these things to
excess. A good rule of thumb is to try and mimic real data configurations that you might
find in the real world. Just for kicks though, let’s put one more array within an array to test
it out.
<?php

$dynamic = array(7, 'House', 'Car', array('grass', array('John Deere', 'Kubota', 'New Holland'),
'mulch'));

echo $dynamic[0].'<br>';
echo $dynamic[1].'<br>';
echo $dynamic[2].'<br>';

echo '<br>';

echo $dynamic[3][0].'<br>';
echo $dynamic[3][1][0].'<br>';
echo $dynamic[3][1][1].'<br>';
echo $dynamic[3][1][2].'<br>';
echo $dynamic[3][2].'<br>';
?>

7
House
Car
grass
John Deere
Kubota
New Holland
mulch
Excellent. See how now that there is an array inside an array inside an array, we just use
triple bracket notation [][][] to get at that data. Is there really a need to go this many
levels deep? Not a lot, but it does help to know how this stuff clicks together, much like our
beloved sophisticated interlocking brick system (Legos).

Look Deep Into The Array


When faced with the task of looking deep into the abyss an array, you can make use of the
ever useful print_r() function to see how the array is structured. It makes data inside of
an array much easier to read. In addition to using the print_r() function, it helps to wrap
the output within html pre tags. Let’s see how this works.
<?php

$dynamic = array(7, 'House', 'Car', array('grass', array('John Deere', 'Kubota', 'New Holland'),
'mulch'));

print_r($dynamic);

echo '<pre>';
print_r($dynamic);

?>

Array ( [0] => 7 [1] => House [2] => Car [3] => Array ( [0] => grass [1] => Array ( [0] =>
John Deere [1] => Kubota [2] => New Holland ) [2] => mulch ) )
Array
(
[0] => 7
[1] => House
[2] => Car
[3] => Array
(
[0] => grass
[1] => Array
(
[0] => John Deere
[1] => Kubota
[2] => New Holland
)

[2] => mulch


)

Notice here that we use the print_r() function a couple of times. The difference is that the
second time, we wrap the output in html pre tags. The pre tags provide a nice formatted
output so that it is easier to see how things nest within the array. See how each time we
reach another array, the output is indented to give us a visual indication that something
interesting is happening here. Put that print_r() function in your back pocket, you’re
going to use it all the time when debugging your code. There is one thing to be aware of
when retrieving data out of your arrays, and that is you need to specify an index that
actually exists or you’ll get an error.
<?php

$dynamic = array(7, 'House', 'Car', array('grass', array('John Deere', 'Kubota', 'New Holland'),
'mulch'));

echo $dynamic[4];

?>

Notice: Undefined offset: 4 in C:wampwwwphpconsoleindex.php(61) : eval()’d code


on line 3
You see we get an undefined offset error if we specify to retrieve data from an index that
does not exist. So it seems we’d like to get data out of index 4 but there is nothing there,
well let’s add some data into that pocket, it’s easy enough to do, check it out.
<?php

$dynamic = array( 7, 'House', 'Car', array('grass', array('John Deere', 'Kubota', 'New Holland'),
'mulch'));
$dynamic[] = 'Bike';

echo $dynamic[4];

?>

Bike
By simply assigning a new value to the variable $dynamic[] using the bracket notation,
PHP knows that you want to add something to the end of the array. Note that you didn’t
even have to indicate that it was position 4 where you wanted to place something, it just
did it for you. Just to bring the idea home, let’s look at one more example.
<?php

$dynamic = array( 7, 'House', 'Car', array('grass', array('John Deere', 'Kubota', 'New Holland'),
'mulch'));
$dynamic[] = 'Bike';

$dynamic[1] = 'Big House';

$dynamic[9] = 'Surf Board';

echo '<pre>';

print_r($dynamic);

?>

Array
(
[0] => 7
[1] => Big House
[2] => Car
[3] => Array
(
[0] => grass
[1] => Array
(
[0] => John Deere
[1] => Kubota
[2] => New Holland
)

[2] => mulch


)

[4] => Bike


[9] => Surf Board
)

This is a neat example here. See how we can easily overwrite and existing index by simply
assigning a new value to it. This is why index 1 no longer has a House in it, but a Big
House in it. Suppose that you need to add something at a specific position, we did that as
well. Note that index 9 now has a Surf Board in it.

Associative Arrays
We’re getting a good handle on arrays in PHP, but we’re not done yet. So far we have
been working with plain old vanilla index based arrays. The standard index based array
relies on numeric keys to work with them. The keys are often invisible to us until we
actually output the full array using a pretty print. Associative arrays are a little different in
that the keys must be specified explicitly using a label of some type. Think of it like a
collection of file folders with labels on them. The label on the folder is the key, while the
contents located inside of the folder is the value. The easiest way to see how this works is
to simply look at some code.
<?php

$dynamic = array( 'number' => 7, 'live' => 'House', 'drive' => 'Car', array('mow' => 'grass',
array('tractor' => 'John Deere', 'tractor2' => 'Kubota', 'tractor3' => 'New Holland'), 'landscape' =>
'mulch'));

echo '<pre>';

print_r($dynamic);

?>

Array
(
[number] => 7
[live] => House
[drive] => Car
[0] => Array
(
[mow] => grass
[0] => Array
(
[tractor] => John Deere
[tractor2] => Kubota
[tractor3] => New Holland
)

[landscape] => mulch


)

Nice Work!We have turned our formerly boring standard array into a fully associative array.
Now we can access this data using named keys of some type instead of only numeric
indices. To be fair, all we did was a pretty print of the contents so let’s look at the actual
syntax we would need to use to access all of this information.
<?php

$dynamic = array( 'number' => 7, 'live' => 'House', 'drive' => 'Car', array('mow' => 'grass',
array('tractor' => 'John Deere', 'tractor2' => 'Kubota', 'tractor3' => 'New Holland'), 'landscape' =>
'mulch'));

echo $dynamic['number'].'<br>';
echo $dynamic['live'].'<br>';
echo $dynamic['drive'].'<br>';
echo $dynamic[0]['mow'].'<br>';
echo $dynamic[0][0]['tractor'].'<br>';
echo $dynamic[0][0]['tractor2'].'<br>';
echo $dynamic[0][0]['tractor3'].'<br>';
echo $dynamic[0]['landscape'].'<br>';

?>

7
House
Car
grass
John Deere
Kubota
New Holland
mulch
Slick!See how instead of putting the number of the index in between the brackets, we now
put in the label, whatever that may be. Note that for arrays within arrays, you might need to
use a combination of index based and associative labels to get at the data you are looking
for just like we did above.
Wrapping Up
We have the basics of PHP arrays covered. Use this and other examples to refine your
skills. Soon we will dig into all of the amazing functions for dealing with arrays that PHP
provides to us, and there are many!
The Top 17 Most Popular PHP Array
Functions

You are going to run into PHP Arrays and PHP array functions with amazing
regularity during the course of your web design and web development. It makes
sense, because arrays are one of the most useful data types we can use. So it
got us to thinking, what would you get if you combined the worlds most
popular PHP CMS applications and dumped all of their source code into one
bucket, then analyzed their most used array functions? Well you would get this
awesome list of course! This is a great way to keep your skills sharp or simply
refreshed when working with Arrays in PHP. Let’s check it out.

• 1array()
• 2is_array()
• 3in_array()
• 4array_merge()
• 5array_keys()
• 6array_key_exists()
• 7array_shift()
• 8array_push()
• 9array_pop()
• 10array_values()
• 11array_map()
• 12array_unique()
• 13array_slice()
• 14array_diff()
• 15array_search()
• 16array_reverse()
• 17 array_unshift()

1. array()
This handy little guy creates an array for you. Here we’ll create an associative array with
two keys, and then place an an associative array inside one and an indexed array inside
the other.
<?php
$array = array (
'websites' => array (
'Search' => 'Google',
'Social' => 'Facebook',
'News' => 'NY Times'
),
'friends' => array (
'Chris',
'Jim',
'Lynn',
'Jeff',
'Joanna'
)
);

print_r ( $array );
?>

And it goes a little something like this, HIT IT:


Array
(
[websites] => Array
(
[Search] => Google
[Social] => Facebook
[News] => NY Times
)

[friends] => Array


(
[0] => Chris
[1] => Jim
[2] => Lynn
[3] => Jeff
[4] => Joanna
)

)
Learn more about array() at http://us1.php.net/manual/en/function.array.php

2. is_array()
Checks whether the variable is an array. Returns TRUE if the variable is an array, and
FALSE otherwise. Used like so:
<?php
echo is_array($array); //1 or TRUE
?>

Learn more about is_array() at http://us2.php.net/manual/en/function.is-array.php

3. in_array()
We may often want to check if a certain value is in one of our arrays. Recall from our
example above that we assigned an indexed array of friends to the ‘friends’ key of our
example array. Let’s see if ‘Jeff’ was included.
<?php
$result = in_array('Jeff', $array['friends']);

print_r($result); // 1 or TRUE or TRUE


?>

Ah ha, turns out he was. With in_array(), the first argument is what you are looking for,
and the second argument is the array you will check in. Learn more
about in_array() at http://us3.php.net/manual/en/function.in-array.php

4. array_merge
Remember we had some websites and friends in the array from the prior example. In fact
we stored an array of values in those arrays. Well I’m feeling lazy and I don’t want to work
with two arrays. I just want to work with one, so let’s merge those two arrays together!
<?php
$array = array (
'websites' => array (
'Search' => 'Google',
'Social' => 'Facebook',
'News' => 'NY Times'
),
'friends' => array (
'Chris',
'Jim',
'Lynn',
'Jeff',
'Joanna'
)
);

$merged = array_merge ( $array ['websites'], $array ['friends'] );

print_r ( $merged );
?>

And bingo bango, we now have one array created out of two!
Array
(
[Search] => Google
[Social] => Facebook
[News] => NY Times
[0] => Chris
[1] => Jim
[2] => Lynn
[3] => Jeff
[4] => Joanna
)

Learn more about array_merge() at http://us3.php.net/manual/en/function.array-merge.php

5. array_keys
Let’s now extract all the keys from our $merged array by adding these lines:
<?php
$keys = array_keys ( $merged );
print_r ( $keys );
?>

And now you can see the keys of our $merged array become the values of the array
returned from array_keys()!
Array
(
[0] => Search
[1] => Social
[2] => News
[3] => 0
[4] => 1
[5] => 2
[6] => 3
[7] => 4
)

Learn more about array_keys() at http://us3.php.net/manual/en/function.array-keys.php

6. array_key_exists()
With array_key_exists() we can perform a validation similar to the way we would
with isset(). You pass a key to search for and an array to search in, and the function will
return TRUE if the key exists in the array provided. Building on our prior example, let’s see
if the 7th key is set:
<?php
$keys = array_keys ( $merged );
$exists = array_key_exists('7', $keys);

print_r ( $exists ); // 1 or TRUE

echo $keys['7']; //The key of 7 has value of 4


?>

Learn more about array_key_exists() at http://us3.php.net/manual/en/function.array-key-


exists.php

7. array_shift()
Let’s remember our original $array which had two keys in it, ‘websites’ and ‘friends’. I want
each key to have it’s own variable name in the program, how can I do that? Well, let’s
apply the array_shift() function to $array, return the result to a variable $shifted, and
examine both variables.
<?php
$array = array (
'websites' => array (
'Search' => 'Google',
'Social' => 'Facebook',
'News' => 'NY Times'
),
'friends' => array (
'Chris',
'Jim',
'Lynn',
'Jeff',
'Joanna'
)
);
$shifted = array_shift ( $array );

print_r ( $array );

print_r ( $shifted );
?>

You can see the ‘websites’ key, which is the first in the array, was shifted out of the array,
while the ‘friends’ key was left intact. Awesome!
// print_r ( $array ); 'friends' is still in the original
Array
(
[friends] => Array
(
[0] => Chris
[1] => Jim
[2] => Lynn
[3] => Jeff
[4] => Joanna
)

)
// print_r ( $shifted ); 'websites' was shifted out
Array
(
[Search] => Google
[Social] => Facebook
[News] => NY Times
)

Learn more about array_shift() at http://us3.php.net/manual/en/function.array-shift.php

8. array_push
Our newly created $shifted variable is mad. It wants back into the original $arrayvariable
to undo the shifting we have caused. Well, let’s try to apply the array_push()function to the
original $array and push $shifted back onto the end of the array:
<?php
$array = array (
'websites' => array (
'Search' => 'Google',
'Social' => 'Facebook',
'News' => 'NY Times'
),
'friends' => array (
'Chris',
'Jim',
'Lynn',
'Jeff',
'Joanna'
)
);

$shifted = array_shift ( $array );

array_push ( $array, $shifted );

print_r ( $array );
?>

You can see friends is now in the first position and the $shifted array is added back to the
original array. Note that array_push() does not keep key => value pairs intact! We have
lost our ‘websites’ key(it is now 0).
Array
(
[friends] => Array
(
[0] => Chris
[1] => Jim
[2] => Lynn
[3] => Jeff
[4] => Joanna
)

[0] => Array


(
[Search] => Google
[Social] => Facebook
[News] => NY Times
)

Learn more about array_push() at http://us3.php.net/manual/en/function.array-push.php

9. array_pop
Fickle mister $shifted is mad about losing his ‘websites’ key. I’m not going to be in
this $array if I can’t have my original key. Ok fine then, we’ll array_pop() you right off the
end of this $array one more time.
<?php
$array = array (
'websites' => array (
'Search' => 'Google',
'Social' => 'Facebook',
'News' => 'NY Times'
),
'friends' => array (
'Chris',
'Jim',
'Lynn',
'Jeff',
'Joanna'
)
);

$shifted = array_shift ( $array );

array_push ( $array, $shifted );

$shifted = array_pop ( $array ); //POP!

print_r ( $array );

print_r ( $shifted );
?>

And there you go mister $shifted – popped off and placed back into your own array.
Array
(
[friends] => Array
(
[0] => Chris
[1] => Jim
[2] => Lynn
[3] => Jeff
[4] => Joanna
)

Array
(
[Search] => Google
[Social] => Facebook
[News] => NY Times
)

Learn more about array_pop() at http://us3.php.net/manual/en/function.array-pop.php

10. array_values
Remember when we created the $merged array earlier and we got a nifty little array looking
like this?
Array
(
[Search] => Google
[Social] => Facebook
[News] => NY Times
[0] => Chris
[1] => Jim
[2] => Lynn
[3] => Jeff
[4] => Joanna
)

Well, I’m not crazy about the fact that some of those keys are named and others are
indexed. I’d like to grab just the values of the $merged array listed only with numeric
indexes. Let use the array_values() function to do just that.
<?php
$array = array (
'websites' => array (
'Search' => 'Google',
'Social' => 'Facebook',
'News' => 'NY Times'
),
'friends' => array (
'Chris',
'Jim',
'Lynn',
'Jeff',
'Joanna'
)
);

$merged = array_merge ( $array ['websites'], $array ['friends'] );

$merged = array_values( $merged ); //get the values

print_r ( $merged );
?>

Ah yes, there she is – my nicely formatted merged array with neat indexes 0 – 7 courtesy
of array_values().
Array
(
[0] => Google
[1] => Facebook
[2] => NY Times
[3] => Chris
[4] => Jim
[5] => Lynn
[6] => Jeff
[7] => Joanna
)
Learn more about array_values() at http://us3.php.net/manual/en/function.array-
values.php

11. array_map
Ok all this array business has me needing a break. Let’s go shopping and buy some cool
new gadgets, maybe a new iPad Air. You know, these days they tax you on everything, so
when we go shopping, let’s not forget that we have to pay a 5% sales tax. We’ll use
our array_map() function to help us there.
<?php
function salestax($price) {
return number_format ( ($price * 1.05), 2, '.', '' );
}

$items = array (
100,
50,
250,
70,
500
);
$finalcost = array_map ( 'salestax', $items );
print_r ( $finalcost );
?>

Ok check it out. We had our array of $items to shop for, but we needed to quickly calculate
the sales tax for each item at a 5% rate. Well with array_map() we can apply a function to
every single array element, and return an array with the newly processed results, in this
case our $finalcost – neat!
Array
(
[0] => 105.00
[1] => 52.50
[2] => 262.50
[3] => 73.50
[4] => 525.00
)

Learn more about array_map() at http://us3.php.net/manual/en/function.array-map.php

12. array_unique
You know there is a lot of blogging going on out there, and the search engines want to
make sure they only index unique articles. Our little internet spider came across some
articles below and put them into the $index. We need to make sure they are unique
however, maybe we can use array_unique() to help us out!
<?php
$index = array (
'How to Eat Apples',
'Surfing Safely in a Wave Pool',
'The Best Foods For Breakfast',
'How to Eat Apples',
'25 tips to blogging nirvana',
'The Best Egg Nogg Recipe for the Holidays'
);
$unique = array_unique ( $index );
print_r ( $unique )
?>

Awesome! Working as designed! Our array_unique() got rid of that duplicate value in the
array and returned us a new array with only unique titles. Did you spot the duplicate title in
the original array?
Array
(
[0] => How to Eat Apples
[1] => Surfing Safely in a Wave Pool
[2] => The Best Foods For Breakfast
[4] => 25 tips to blogging nirvana
[5] => The Best Egg Nogg Recipe for the Holidays
)

Learn more about array_unique() at http://us3.php.net/manual/en/function.array-


unique.php

13. array_slice
Come to think of it, rather than use that array_unique() on our $index, let’s go ahead and
perform some surgery on that array and extract only the inner elements, leaving the first
and last entry to their own devices.
<?php
$index = array (
'How to Eat Apples',
'Surfing Safely in a Wave Pool',
'The Best Foods For Breakfast',
'How to Eat Apples',
'25 tips to blogging nirvana',
'The Best Egg Nogg Recipe for the Holidays'
);
$surgerized = array_slice ( $index, 1, 4 ); //slice it
print_r ( $surgerized );
?>

And there you have it, by passing the array to work on, the starting offset, and the length of
our extraction, we have successfully removed the middle 4 entries of our 6 element array.
Bravo!
Array
(
[0] => Surfing Safely in a Wave Pool
[1] => The Best Foods For Breakfast
[2] => How to Eat Apples
[3] => 25 tips to blogging nirvana
)

Learn more about array_slice() at http://us3.php.net/manual/en/function.array-slice.php

14. array_diff
Ok friends, our internet spider has been busy and it has created an updated index after
some time. We’d like to examine our first index in comparison to the second and see
what’s new. Let’s do it with our array_diff() function!
<?php
$index = array (
'How to Eat Apples',
'Surfing Safely in a Wave Pool',
'The Best Foods For Breakfast',
'How to Eat Apples',
'25 tips to blogging nirvana',
'The Best Egg Nogg Recipe for the Holidays'
);

$index2 = array (
'How to Eat Apples',
'Surfing Safely in a Wave Pool',
'The Best Foods For Breakfast',
'How to Eat Apples',
'25 tips to blogging nirvana',
'The Best Egg Nogg Recipe for the Holidays',
'Arrays with Style',
'PHP in the Enterprise',
'Douglas Crockford declares PHP his favorite language'
);
$diff = array_diff ( $index2, $index );
print_r ( $diff );
?>
Awesome. Our internet spider has found 3 new articles on the internet titled, ‘Arrays with
Style’, ‘PHP in the Enterprise’, and ‘Douglas Crockford declares PHP his favorite
language’. By passing our updated index and original index to the array_diff()function, it
returned only the new results to us.
Array
(
[6] => Arrays with Style
[7] => PHP in the Enterprise
[8] => Douglas Crockford declares PHP his favorite language
)

Learn more about array_diff() at http://us3.php.net/manual/en/function.array-diff.php

15. array_search
My buddy was telling me about a cool article named ‘PHP in the Enterprise’, I wonder if our
updated index was able to capture it yet? Let’s find out with array_search();
<?php
$index2 = array (
'How to Eat Apples',
'Surfing Safely in a Wave Pool',
'The Best Foods For Breakfast',
'How to Eat Apples',
'25 tips to blogging nirvana',
'The Best Egg Nogg Recipe for the Holidays',
'Arrays with Style',
'PHP in the Enterprise',
'Douglas Crockford declares PHP his favorite language'
);
$found = array_search ( 'PHP in the Enterprise', $index2 ); // (needle,haystack)
print_r ( $found ); // 7
?>

Well isn’t that cool? We see that it is in fact in the index at position 7, as returned
from array_search()
Learn more about array_search() at http://us3.php.net/manual/en/function.array-
search.php

16. array_reverse
When you want to turn an array upside down or rightside up, you can use
the array_reverse() function. I have added some elements to our original $array so we
can get a better feel for how array_reverse() treats the array with both associative and
indexed properties.
<?php
$array = array (
'websites' => array (
'Search' => 'Google',
'Social' => 'Facebook',
'News' => 'NY Times'
),
'friends' => array (
'Chris',
'Jim',
'Lynn',
'Jeff',
'Joanna'
),
16,
99,
13,
'newfriend' => 'Ken'
);

print_r ( $array );

$array = array_reverse ( $array );

print_r ( $array );
?>

And here we see the results of applying the array_reverse() to our $array
// before reverse
Array
(
[websites] => Array
(
[Search] => Google
[Social] => Facebook
[News] => NY Times
)

[friends] => Array


(
[0] => Chris
[1] => Jim
[2] => Lynn
[3] => Jeff
[4] => Joanna
)

[0] => 16
[1] => 99
[2] => 13
[newfriend] => Ken
)

// after reverse
Array
(
[newfriend] => Ken
[0] => 13
[1] => 99
[2] => 16
[friends] => Array
(
[0] => Chris
[1] => Jim
[2] => Lynn
[3] => Jeff
[4] => Joanna
)

[websites] => Array


(
[Search] => Google
[Social] => Facebook
[News] => NY Times
)

Learn more about array_reverse() at http://us3.php.net/manual/en/function.array-


reverse.php

17. array_unshift
We have seen how easy it is to add items to the end of an array, but what if we need to
prepend something to our array? Well that is where our nifty little array_unshift()comes
in. Let’s see how it works by adding an interest of ‘music’ to our array:
<?php
$array = array (
'websites' => array (
'Search' => 'Google',
'Social' => 'Facebook',
'News' => 'NY Times'
),
'friends' => array (
'Chris',
'Jim',
'Lynn',
'Jeff',
'Joanna'
),
16,
99,
13,
'newfriend' => 'Ken'
);

array_unshift( $array, 'music');

print_r ( $array );
?>

Alrighty then! Check out that interest of music at the beginning of our array!
Array
(
[0] => music
[websites] => Array
(
[Search] => Google
[Social] => Facebook
[News] => NY Times
)

[friends] => Array


(
[0] => Chris
[1] => Jim
[2] => Lynn
[3] => Jeff
[4] => Joanna
)

[1] => 16
[2] => 99
[3] => 13
[newfriend] => Ken
)

Maybe you’d rather prepend an associative keyed value rather than a numeric, in that case
you can simply add your original array to a key value pair like so:
<?php
$array = array ( 'interests' => 'music' ) + $array;

print_r ( $array );
?>

Array
(
[interests] => music
[websites] => Array
(
[Search] => Google
[Social] => Facebook
[News] => NY Times
)

[friends] => Array


(
[0] => Chris
[1] => Jim
[2] => Lynn
[3] => Jeff
[4] => Joanna
)

[0] => 16
[1] => 99
[2] => 13
[newfriend] => Ken
)

Well there you have it friends, an epic journey through the most widely used PHP array
functions!

The 27 Most Useful PHP Array Functions


You Need To Know!

Now that we know exactly what Arrays in PHP are and how they work, what
does PHP the language offer us in terms of working with arrays? Surely we’ll
need to be able to count values in them, sort arrays by their contents, convert
them between strings and arrays, find unique values, search within arrays,
compare arrays to other arrays and more. PHP has got you covered with over
80, that’s right count them, functions to provide any type of operation you could
ever want to perform on an array. In this episode we’ll take a look at the very
most useful PHP array functions so that we can hit the ground running with
arrays. Let’s dig in!

• 1is_array()
• 2in_array()
• 3array_unique()
• 4array_search()
• 5array_reverse()
• 6array_map()
• 7array_diff()
• 8count()
• 9max()
• 10min()
• 11array_rand()
• 12array_count_values()
• 13sort()
• 14asort()
• 15rsort()
• 16arsort()
• 17implode()
• 18explode()
• 19array_key_exists()
• 20array_keys()
• 21array_values()
• 22array_push()
• 23array_pop()
• 24array_unshift()
• 25array_shift()
• 26array_splice()
• 27array_merge()

Array Utility Type Functions


First off, we’ll look at some basic utility type functions for working with arrays in PHP.
Things like checking to see if a variable is an array, looking inside of an array, and so on.
1. is_array(mixed $var)
You might want to know if a variable is an array. If you created it yourself, you’ll know, but
what if this is a value that came from a remote api, or database, or some other means.
You’ll need to check that variable to see what it is and this is how to do it. The function
signature states it can take a mixed variable. That means, just pass in any old variable you
want no matter what it is. If it is an array, the function will return true, otherwise it will
return false.
<?php

$dynamic = [
'number' => 7,
'live' => 'House',
'drive' => 'Car',
[
'mow' => 'grass',
[
'tractor' => 'John Deere',
'tractor2' => 'Kubota',
'tractor3' => 'New Holland'
],
'landscape' => 'mulch'
]
];

$one = is_array($dynamic);

$two = is_array($dynamic['number']);

$three = is_array($dynamic[0]);

echo $one ? 'The $dynamic variable is an array<br>' : 'The $dynamic variable is not an array<br>';
echo $two ? 'The "number" key of the $dynamic variable is an array<br>' : 'The "number" key of the
$dynamic variable is not an array<br>';
echo $three ? 'The 0 index of the $dynamic variable is an array<br>' : 'The 0 index of the $dynamic
variable is not an array<br>';

?>

The $dynamic variable is an array


The “number” key of the $dynamic variable is not an array
The 0 index of the $dynamic variable is an array
By using our array of things we created earlier, we can check to confirm what data
Cool!
types are stored in that array. We have numbers, strings, and arrays, and this code shows
how to check for those scenarios.
2. in_array( mixed $needle , array $haystack [, bool $strict = FALSE ] )
Sometimes there will be instances where an array is quite large containing maybe
hundreds or thousands of values. You might need to check if a certain value is in an array
and with this function you can do that. The function signature requires you to pass in a
needle to search for, an array as the haystack, and optionally a strict flag with will perform
a value and type sensitive search. Watch this function in action now.
<?php
$veggies = ["Spinach", "Corn", "Carrots", "Tomatoes"];

if (in_array("Tomatoes", $veggies)) {
echo "The best Tomatoes make the best Red Sauce!<br>";
}

if (in_array("Snickers Bar", $veggies)) {


echo "Eating a Snickers is Great.";
}

$dynamic = [
'number' => 7,
'live' => 'House',
'drive' => 'Car',
[
'mow' => 'grass',
[
'tractor' => 'John Deere',
'tractor2' => 'Kubota',
'tractor3' => 'New Holland'
],
'landscape' => 'mulch'
]
];

$tractor = $dynamic[0][0]['tractor'];

if (in_array('grass', $dynamic[0])) {
echo "Time to take a spin on the $tractor and get the grass cut!<br>";
}
?>

The best Tomatoes make the best Red Sauce!


Time to take a spin on the John Deere and get the grass cut!
3. array_unique( array $array [, int $sort_flags = SORT_STRING ] )
This is a fantastic function to use and it’s use case is to get rid of any duplicate values in
the array you provide to it. Say you run a regular expression match on a piece of text and
you get back hundreds of matches in the results all stored in an array. Well, we don’t need
duplicates, so we can simply apply the array_unique function to get what we want. In this
example we’ll take an array of strings that has many duplicates and screen them out.
<?php
$array = [
'Ten Steps To a Better You',
'Ten Steps To a Better You',
'Ten Steps To a Better You',
'Eating Spiniach - The Pros Show You How',
'Eating Spiniach - The Pros Show You How',
'Falling in Love with Arrays',
'Falling in Love with Arrays',
'Stock Market Secrects Jim Cramer Will Not Share',
'Uplifting News by ZeroHege',
'Uplifting News by ZeroHege'
];
$unique = array_unique($array);

foreach ($unique as $u) {


echo $u . '<br>';
}
?>

Ten Steps To a Better You


Eating Spiniach – The Pros Show You How
Falling in Love with Arrays
Stock Market Secrects Jim Cramer Will Not Share
Uplifting News by ZeroHege
4. array_search( mixed $needle , array $haystack [, bool $strict = false ] )
The array_search function is very handy for finding a value in an array and determining
where it lives. That is to say, this function provides to you the index or key for the value
you are searching for. Let’s see how it works here.
<?php
$array = [
'How to build a website',
'Design with Twitter Bootstrap',
'Handle the backend with PHP',
'Eat Veggies for good health',
'The answers to all of your questions',
'Racing in the Nascar Series'
];

$index = array_search('The answers to all of your questions', $array);

echo "The answers to all of your questions is located at index $index of the array."
?>

The answers to all of your questions is located at index 4 of the array.


5. array_reverse( array $array [, bool $preserve_keys = false ] )
It’s really easy to take an array and reverse it’s order. With this function you also have the
option to keep the keys in tact or not. Let’s test it out.
<?php
$array = [
'How to build a website',
'Design with Twitter Bootstrap',
'Handle the backend with PHP',
'Eat Veggies for good health',
'The answers to all of your questions',
'Racing in the Nascar Series'
];
$array1 = array_reverse($array);
$array2 = array_reverse($array, true);

foreach ($array1 as $a => $b) {


echo $a . ' - ' . $b . '<br>';
}

echo '<br>';

foreach ($array2 as $a => $b) {


echo $a . ' - ' . $b . '<br>';
}
?>

0 – Racing in the Nascar Series


1 – The answers to all of your questions
2 – Eat Veggies for good health
3 – Handle the backend with PHP
4 – Design with Twitter Bootstrap
5 – How to build a website
5 – Racing in the Nascar Series
4 – The answers to all of your questions
3 – Eat Veggies for good health
2 – Handle the backend with PHP
1 – Design with Twitter Bootstrap
0 – How to build a website
6. array_map( callable $callback , array $array1 [, array $… ] )
The array_map function is pretty useful in that you can run a function on every single
element in the array. You need to define a function, then that function name is given to the
array_map function as the first parameter, and the second parameter is the array to iterate
over. Let’s turn our array of mixed case strings into all lowercase.
<?php
$array = [
'How to build a website',
'Design with Twitter Bootstrap',
'Handle the backend with PHP',
'Eat Veggies for good health',
'The answers to all of your questions',
'Racing in the Nascar Series'
];

function lower($array)
{
return strtolower($array);
}

$lc = array_map('lower', $array);


foreach ($lc as $l) {
echo $l . '<br>';
}
?>

how to build a website


design with twitter bootstrap
handle the backend with php
eat veggies for good health
the answers to all of your questions
racing in the nascar series
7. array_diff( array $array1 , array $array2 [, array $… ] )
The array_diff function compares one or more arrays and provides only the values present
in array one, that are not in any other arrays. Let’s see how it works.
<?php
$arrayone = [
'Google',
'Microsoft',
'Apple',
'Adobe',
'Cisco',
'Juniper',
'Lenovo',
'Samsung',
'Red Hat'
];

$arraytwo = [
'Google',
'Microsoft',
'Apple',
'Adobe',
'Cisco',
'Juniper',
'Lenovo',
'Samsung'
];

$diff = array_diff($arrayone, $arraytwo);

print_r($diff);

Array ( [8] => Red Hat )

Array Counting Functions


Now that we have some useful utility type array functions covered, let’s look at some array
functions related to counting values or dealing with numbers. We can count the number of
things in an array, return the maximum or minimum value, and all kinds of other useful
hacks. Let’s see how.
8. count( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
The best way to see how this great function works is to simply put it into action!
<?php
$dynamic = [
'number' => 7,
'live' => 'House',
'drive' => 'Car',
[
'mow' => 'grass',
[
'tractor' => 'John Deere',
'tractor2' => 'Kubota',
'tractor3' => 'New Holland'
],
'landscape' => 'mulch'
]
];

$veggies = ["Spinach", "Corn", "Carrots", "Tomatoes", "Cucumbers"];

$tractor = $dynamic[0][0];

$tech = [
'Google',
'Microsoft',
'Apple',
'Adobe',
'Cisco',
'Juniper',
'Lenovo',
'Samsung',
'Red Hat'
];

$v1 = count($dynamic);
$v2 = count($veggies);
$v3 = count($tractor);
$v4 = count($tech);

echo "We have $v1 items in the dynamic array, $v2 vegetables, $v3 tractors, and $v4 tech companies.
Thanks for using the count function.";

We have 4 items in the dynamic array, 5 vegetables, 3 tractors, and 9 tech


companies. Thanks for using the count function.
9. max( array $values )
Finds the max value in the array.
10. min( array $values )
Finds the min value in the array.
11. array_rand( array $array [, int $num = 1 ] )
Returns a random value from an array. We’ll test all three of these functions in one shot.
<?php

$numbers = ['12', '234651', '234', '41', '89', '196583', '1', '86', '3', '5', '9'];

echo max($numbers) . '<br>';

echo min($numbers) . '<br>';

$rand = array_rand($numbers);

echo $rand;
<?php

$numbers = ['12', '234651', '234', '41', '89', '196583', '1', '86', '3', '5', '9'];

echo max($numbers) . '<br>';

echo min($numbers) . '<br>';

$rand = array_rand($numbers);

echo $rand;

234651
1
4
12. array_count_values( array $array )
This is an incredible array function you can make use of. What it does is take an array with
many values, and then counts the number of times each value occurs in the array. It does
this by turning the original array’s values into keys in the new array, and assigns a number
count for how many times that value occurred originally as the new value. An example is in
order. Say we had a huge array of stock ticker symbols. In this array there are tons of
entries that occur many many times. We’ll use this function to count how many times each
ticker is present.
<?php

$stocktickers = ['aapl', 'aapl', 'aapl', 'goog', 'goog', 'yhoo', 'fslr', 'msft', 'csco', 'csco'];

$values = array_count_values($stocktickers);
print_r($values);
?>

Array ( [aapl] => 3 [goog] => 2 [yhoo] => 1 [fslr] => 1 [msft] => 1 [csco] => 2 )

Array Sorting Functions


There are a plethora of functions to do all kinds of sorts on your arrays. We’ll take a quick
look at the common ones now. What we can do is take a few of our arrays so far and apply
the various sorts to them. The behavior will be different based on the types that are in the
array and so on. The best case scenario is you simply test the function in question before
trying to use it in your program. There is a special point to notice about these following four
functions. Take note that the array passed in begins with an & in the function signature.
What this means is that these functions are destructive. That is to say, they directly modify
the array in memory, they do not create a copy of the original. This is something to keep in
mind when sorting arrays.
13. sort( array &$array [, int $sort_flags = SORT_REGULAR ] )
14. asort( array &$array [, int $sort_flags = SORT_REGULAR ] )
15. rsort( array &$array [, int $sort_flags = SORT_REGULAR ] )
16. arsort( array &$array [, int $sort_flags = SORT_REGULAR ] )
<?php
$mixed = [
'number' => 7,
'live' => 'House',
'drive' => 'Car',
[
'mow' => 'grass',
[
'tractor' => 'John Deere',
'tractor2' => 'Kubota',
'tractor3' => 'New Holland'
],
'landscape' => 'mulch'
]
];

$veggies = ["Spinach", "Corn", "Carrots", "Tomatoes", "Cucumbers"];

$tech = [
'Google',
'Microsoft',
'Apple',
'Adobe',
'Cisco',
'Juniper',
'Lenovo',
'Samsung',
'Red Hat'
];
$stocktickers = ['aapl', 'aapl', 'aapl', 'goog', 'goog', 'yhoo', 'fslr', 'msft', 'csco', 'csco'];

$numbers = ['12', '234651', '234', '41', '89', '196583', '1', '86', '3', '5', '9'];

echo '<pre>';

sort($mixed);
sort($veggies);
sort($stocktickers);
sort($numbers);

print_r($mixed);
print_r($veggies);
print_r($stocktickers);
print_r($numbers);

// sort($mixed);
Array
(
[0] => Car
[1] => House
[2] => 7
[3] => Array
(
[mow] => grass
[0] => Array
(
[tractor] => John Deere
[tractor2] => Kubota
[tractor3] => New Holland
)

[landscape] => mulch


)

)
// sort($veggies);
Array
(
[0] => Carrots
[1] => Corn
[2] => Cucumbers
[3] => Spinach
[4] => Tomatoes
)

// sort($stocktickers);
Array
(
[0] => aapl
[1] => aapl
[2] => aapl
[3] => csco
[4] => csco
[5] => fslr
[6] => goog
[7] => goog
[8] => msft
[9] => yhoo
)
// sort($numbers);
Array
(
[0] => 1
[1] => 3
[2] => 5
[3] => 9
[4] => 12
[5] => 41
[6] => 86
[7] => 89
[8] => 234
[9] => 196583
[10] => 234651
)

// asort($mixed);
Array
(
[drive] => Car
[live] => House
[number] => 7
[0] => Array
(
[mow] => grass
[0] => Array
(
[tractor] => John Deere
[tractor2] => Kubota
[tractor3] => New Holland
)

[landscape] => mulch


)

)
// asort($veggies);
Array
(
[2] => Carrots
[1] => Corn
[4] => Cucumbers
[0] => Spinach
[3] => Tomatoes
)
// asort($stocktickers);
Array
(
[0] => aapl
[2] => aapl
[1] => aapl
[8] => csco
[9] => csco
[6] => fslr
[4] => goog
[3] => goog
[7] => msft
[5] => yhoo
)
// asort($numbers);
Array
(
[6] => 1
[8] => 3
[9] => 5
[10] => 9
[0] => 12
[3] => 41
[7] => 86
[4] => 89
[2] => 234
[5] => 196583
[1] => 234651
)

// rsort($mixed);
Array
(
[0] => Array
(
[mow] => grass
[0] => Array
(
[tractor] => John Deere
[tractor2] => Kubota
[tractor3] => New Holland
)

[landscape] => mulch


)

[1] => 7
[2] => House
[3] => Car
)
// rsort($veggies);
Array
(
[0] => Tomatoes
[1] => Spinach
[2] => Cucumbers
[3] => Corn
[4] => Carrots
)
// rsort($stocktickers);
Array
(
[0] => yhoo
[1] => msft
[2] => goog
[3] => goog
[4] => fslr
[5] => csco
[6] => csco
[7] => aapl
[8] => aapl
[9] => aapl
)
// rsort($numbers);
Array
(
[0] => 234651
[1] => 196583
[2] => 234
[3] => 89
[4] => 86
[5] => 41
[6] => 12
[7] => 9
[8] => 5
[9] => 3
[10] => 1
)

// arsort($mixed);
Array
(
[0] => Array
(
[mow] => grass
[0] => Array
(
[tractor] => John Deere
[tractor2] => Kubota
[tractor3] => New Holland
)

[landscape] => mulch


)

[number] => 7
[live] => House
[drive] => Car
)
// arsort($veggies);
Array
(
[3] => Tomatoes
[0] => Spinach
[4] => Cucumbers
[1] => Corn
[2] => Carrots
)
// arsort($stocktickers);
Array
(
[5] => yhoo
[7] => msft
[3] => goog
[4] => goog
[6] => fslr
[9] => csco
[8] => csco
[1] => aapl
[0] => aapl
[2] => aapl
)
// arsort($numbers);
Array
(
[1] => 234651
[5] => 196583
[2] => 234
[4] => 89
[7] => 86
[3] => 41
[0] => 12
[10] => 9
[9] => 5
[8] => 3
[6] => 1
)

Converting Between Arrays and Strings


Converting between arrays and strings happens all the time. As such, PHP provides the
implode and explode functions. They are quite easy to use and work just like their names
imply. implode takes in an array and glues it together as one big string while explode takes
in a string and delimiter and explodes that string into pieces based on the delimiter
provided. Let’s check them out.
17. implode( string $glue , array $pieces )
18. explode( string $delimiter , string $string [, int $limit ] )
<?php

$glue = '*';

$pieces = ['Yaba', 'Daba', 'Doo', 'Who', 'Loves', 'You', '?'];

echo implode($glue, $pieces);

?>

Yaba*Daba*Doo*Who*Loves*You*?
<?php

$glue = '*';

$pieces = ['Yaba', 'Daba', 'Doo', 'Who', 'Loves', 'You', '?'];

$string = implode($glue, $pieces);

$array = explode('*', $string);

print_r($array);

?>

Array
(
[0] => Yaba
[1] => Daba
[2] => Doo
[3] => Who
[4] => Loves
[5] => You
[6] => ?
)

General Manipulation Functions


Last up we have a handful of general array manipulation functions that you are most likely
to come across in your day to day programming. Let’s take a look at a few of these now.
19. array_key_exists( mixed $key , array $array )
We can check to see if a certain key exists in our array with this handy function. This is
how to use it.
<?php

$array = [
'phone' => 'iPhone',
'laptop' => 'Carbon X1',
'car' => 'Tesla',
];

$true = array_key_exists('laptop', $array);

echo 'Do you have a laptop? ';

if ($true) {
echo 'Why yes, yes I do in fact.';
} else {
echo 'No I use my tablet instead';
}

?>

Do you have a laptop? Why yes, yes I do in fact.


20. array_keys( array $array [, mixed $search_value [, bool $strict = false ]] )
This function allows us to quickly see all of the keys of the array, but not the values. Here
is how to do that.
<?php

$array = [
'phone' => 'iPhone',
'laptop' => 'Carbon X1',
'car' => 'Tesla',
];

$keys = array_keys($array);

print_r($keys);

?>

Array
(
[0] => phone
[1] => laptop
[2] => car
)

21. array_values( array $array )


What about if we want to see all the values of the array instead of the keys? How can we
accomplish that? Just like this!
<?php

$array = [
'phone' => 'iPhone',
'laptop' => 'Carbon X1',
'car' => 'Tesla',
];

$values = array_values($array);

print_r($values);

?>

Array
(
[0] => iPhone
[1] => Carbon X1
[2] => Tesla
)

22. array_push( array &$array , mixed $value1 [, mixed $… ] )


Now we come into using the push, pop, unshift, and shift array functions. These deal with
adding things to the end of the array, removing things from the end of the array, adding
things to the begging of an array, and removing things from the beginning of an array
respectively. Let’s see them in action.
<?php

$array = [
'Apples',
'Blueberries',
'Pumpkins',
'Corn',
];

array_push($array, 'Watermelons');

echo '<pre>';

print_r($array);

?>

Array
(
[0] => Apples
[1] => Blueberries
[2] => Pumpkins
[3] => Corn
[4] => Watermelons
)

23. array_pop( array &$array )


<?php

$array = [
'Apples',
'Blueberries',
'Pumpkins',
'Corn',
'Watermelons',
];

$yummy = array_pop($array);

echo "Would you like some delicious $yummy?";

?>

Would you like some delicious Watermelons?


24. array_unshift( array &$array , mixed $value1 [, mixed $… ] )
<?php

$array = [
'Apples',
'Blueberries',
'Pumpkins',
'Corn',
'Watermelons',
];

array_unshift($array, 'Apple Pies');

echo '<pre>';

print_r($array);

?>

Array
(
[0] => Apple Pies
[1] => Apples
[2] => Blueberries
[3] => Pumpkins
[4] => Corn
[5] => Watermelons
)

25. array_shift( array &$array )


<?php

$array = [
'Apple Pies',
'Apples',
'Blueberries',
'Pumpkins',
'Corn',
'Watermelons',
];

$eat = array_shift($array);

echo "Let us eat some $eat together!";

?>

Let us eat some Apple Pies together!


26. array_splice( array &$input , int $offset [, int $length [, mixed $replacement = array() ]] )
<?php

$array = [
'Apple Pies',
'Apples',
'Blueberries',
'Pumpkins',
'Corn',
'Watermelons',
];

array_splice($array, 3, 1, 'Chocolates');

print_r($array);

?>

Array
(
[0] => Apple Pies
[1] => Apples
[2] => Blueberries
[3] => Chocolates
[4] => Corn
[5] => Watermelons
)

27. array_merge( array $array1 [, array $… ] )


<?php

$eats = [
'Apple Pies',
'Apples',
'Blueberries',
'Pumpkins',
'Corn',
'Watermelons',
];

$drinks = [
'Water',
'Apple Juice',
'Craft Beer',
'Iced Tea',
'Coffee',
];

$dinner = array_merge($eats, $drinks);

echo '<pre>';

print_r($dinner);

?>

Array
(
[0] => Apple Pies
[1] => Apples
[2] => Blueberries
[3] => Pumpkins
[4] => Corn
[5] => Watermelons
[6] => Water
[7] => Apple Juice
[8] => Craft Beer
[9] => Iced Tea
[10] => Coffee
)

Well friends as they say in show biz, “That’s a WRAP!” We covered a ton of ground in this
episode of our Awesome PHP Tutorial Series. Hopefully you found some of the tips and
tricks useful and can apply them to your own projects.

The Top 9 Most Popular PHP String


Functions
Strings are everywhere in our lives and in our programming. When we think of
reading text, what we’re really doing is reading strings in a sense. In PHP a
string is just an array of characters. There are several ways to define strings,
and many ways to use the built in PHP functions to operate on them. Let’s take
a look at the various ways we can define strings, and then we’ll cover The Top
9 Most Popular PHP String Functions, similar to our popular most used array
functions in PHP blog post. Let’s jump in!

Defining Strings in PHP


There are three main ways to define strings in PHP. We have:

• Characters enclosed in double quotes.


• Characters enclosed in single quotes.
• Characters or lines of characters enclosed by heredoc symbols

Double Quotes
Double quotes are useful when you have a PHP variable you want to embed within the
string, since when the PHP runs, it will use interpolation to grab the actual value of that
variable.
<?php
$str = "Hi buddy, I'm a PHP String";

Single Quotes
Some people find it easier to leave their variables out of strings and let them be more hard
coded sort to speak. Use single quotes for that.
<?php
$str = 'Hi again, still a PHP String!';
Heredoc Syntax
<?php
$str = <<<EOD
Wordpress is really cool
HTML5 is the key to the open web
Who likes to use Twitter Bootstrap
We can have several lines here!
EOD;

Note: You don’t have to use EOD as your delimiter, you can use anything you like as long
as they are the same!

Most Popular PHP String Functions


1. substr()
The substr() function helps you to access a substring between given start and end points
of a string. It can be useful when you need to get at parts of fixed format strings.
The substr() function prototype is as follows:
string substr(string string, int start[, int length] );

The return value is a substring copied from within string.


<?php
$blog = 'Your Blog is Excellent!';

When you call the function with a positive number for start (only), you will get the string
from the start position to the end of the string.
<?php
$blog = 'Your Blog is Excellent!';
substr($blog, 1);
// returns 'our Blog is Excellent!'

String position starts from 0, just like arrays.


When you call substr() with a negative start (only), you will get the string from the end of
the string minus start characters to the end of the string.
<?php
$blog = 'Your Blog is Excellent!';
substr($blog, -9);
// returns 'xcellent!'
The length parameter can be used to specify either a number of characters to return if it is
positive, or the end character of the return sequence if it is negative.
<?php
$blog = 'Your Blog is Excellent!';
substr($blog, 0, 4);
// returns 'Your'

substr($blog, 5, -13);
//returns 'Blog'

5 signifies the starting character point (B) and -13 determines the ending point (count 13
places backwards starting from the end of the string).
Learn more about substr() at http://us3.php.net/substr

2. strlen()
Next up we have the popular strlen() function for checking the length of a string. If you
pass it a string, strlen() will return its length.
<?php
echo strlen("Super Cali Fragilistics Expy Ali Docious");
// 40

Often times this function is used for validating input data or making sure a string variable
has a value.
<?php
$super = 'duper';

if (strlen ( $super ) > 0) {


echo 'Thanks for giving super some duper';
} else {
echo 'That might not have worked';
}
?>
// Thanks for giving super some duper

Learn more about strlen() at http://us3.php.net/strlen

3. str_replace()
Find and replace functionality is super useful with strings. You can use find and replace for
almost anything your imagination can think of.
The most commonly used string function for replacement is str_replace(). It has the
following prototype:
mixed str_replace(mixed needle, mixed new_needle, mixed haystack[, int &count]));

str_replace() replaces all the instances of needle in haystack with new_needle and
returns the new version of the haystack.The optional fourth parameter contains the number
of replacements made.
A really awesome feature of str_replace() is the ability to pass an array to both the
search terms and replace terms, as well as an array of strings to apply the rules to!
<?php
$strings = array (
'You like to have a fun time',
'You are a really nice person',
'Would you like to have a cup of coffee?'
);

$search = array (
'fun',
'time',
'person',
'coffee'
);
$replace = array (
'excellent',
'adventure',
'individual',
'joe'
);

$replaced = str_replace ( $search, $replace, $strings );

print_r ( $replaced );

/////////////////////////////////
Array
(
[0] => You like to have a excellent adventure
[1] => You are a really nice individual
[2] => Would you like to have a cup of joe?
)
?>

Learn more about str_replace() at http://php.net/manual/en/function.str-replace.php


4. trim()
The first step in tidying up data is to trim any excess whitespace from the string. This is a
good idea to prepare for a database insert or string comparison.
The trim() function strips whitespace from the start and end of a string and returns the
resulting string. The characters it strips by default are newlines and carriage returns (n and
r), horizontal and vertical tabs (t and x0B), end-of-string characters (), and spaces. You
can also pass it a second parameter containing a list of characters to strip instead of this
default list. Depending on your particular purpose, you might like to use
the ltrim() or rtrim() functions instead which perform the same operation, but you
choose which side of the string to affect.
Here we remove some literal junk from the beginning and end of our string:
<?php
$trimit = 'junk awesome stuff junk';

$trimmed = trim ( $trimit, 'junk' );

print_r ( $trimmed );

// awesome stuff
?>

Learn more about trim() at http://us2.php.net/manual/en/function.trim.php

5. strpos()
The function strpos() operates in a similar fashion to strstr(), except, instead of
returning a substring, it returns the numerical position of a needle within a haystack.
The strpos() function has the following prototype:
int strpos(string haystack, string needle, int [offset] );

The integer returned is the position of the first occurrence of the needle within the
haystack. The first character is in position 0 just like arrays.
We can see by running the following code that our exclamation point is at position 13.
<?php
$awesome = "Super Awesome!";
echo strpos($awesome, "!");
// 13
This function accepts a single character as the needle, but it can accept a string of any
length. The optional offset parameter determines the point within the haystack to start
searching.
<?php
$awesome = "Super Awesome!";
echo strpos($awesome, ‘m’, 3);
// 11

This code echoes the value 11 to the browser because PHP has started looking for the
character ‘m’ at position 3.
In any of these cases, if the needle is not in the string, strpos() will return false. To avoid
strange behavior you can use the === operator to test return values:
<?php
$awesome = "Super Awesome!";

$result = strpos ( $awesome, G );


if ($result === false) {
echo 'Not found';
} else {
echo 'Found at position ' . $result;
}

// Not found
?>

Learn more about strpos() at http://us2.php.net/strpos

6. strtolower()
Very often in PHP we need to compare strings or correct capitalization when people
SHOUT or do odd things. In order to compare strings, you want to make sure they are the
same case. We can use strtolower() for this purpose. We’ll use a function created
with strtolower() to calm down an angry person.
<?php
function calm_down($string) {

return strtolower ( $string );


}

$person = 'Angry people SHOUT!';

echo calm_down ( $person );


// angry people shout!
?>
Learn more about strtolower() at http://us3.php.net/strtolower

7. strtoupper()
strtoupper() is also quite popular for many of the reasons listed above, in reverse,
meaning take lowercase or a mixed case string and set it to all upper case. We’ll change
things up and create a wake up function to get our workers going in the morning.
<?php
function wake_up($string) {

return strtoupper ( $string );


}

$person = 'these people need to get working!';

echo wake_up ( $person );


// THESE PEOPLE NEED TO GET WORKING!
?>

Learn more about strtoupper() at http://us3.php.net/strtoupper

8. is_string()
is_string() is used to check if a value is a string. Let’s take a look at this within an if()
statement to take an action on strings in one way and non-strings in
another. is_string() returns true or false.
<?php
if (is_string ( 7 )) {
echo "Yes";
} else {
echo "No";
}
// No

if (is_string ( "Lucky Number 7" )) {


echo "Yes";
} else {
echo "No";
}
// Yes
?>

Learn more about is_string() at http://us2.php.net/is_string


9. strstr()
Last but not least we have the strstr() function. The function strstr() can be used to
find a string or character match within a longer string. This function can be used to find a
string inside a string, including finding a string containing only a single character.
The function prototype for strstr() is as follows:
string strstr(string haystack, string needle);

You pass strstr() a haystack to be searched and a needle to be found. If an exact match
of the needle is found, the strstr() function returns the haystack from the needle onward.
If it does not find the needle, it will return false. If the needle occurs more than once, the
returned string will begin from the first occurrence of the needle.
As an example, let’s say we have a submission form for people to submit their website, but
we would like it in a certain format. We can use strstr() to check for a string within a
string to help us here:
<?php
$url = 'vegibit.com';

if (strstr ( $url, 'http://www.' ) === false) {


$url = 'http://www.' . $url;
}

echo $url;
// http://www.vegibit.com
?>

Learn more about strstr() at http://us2.php.net/strstr


By getting a mastery of these very commonly used string functions, you’ll be well on your
way to getting all kinds of tasks completed in your applications. If you enjoyed this tutorial,
you may also enjoy our JavaScript String Functions tutorial as well!

What are Functions in PHP


It’s good to encapsulate code you need to run over and over again inside of a
function so you don’t have to type it out over and over. Code resuse and
keeping it DRY (Don’t Repeat Yourself) is key to providing a maintainable
application. A function is simply a piece of PHP code that you can call and it
may or may not have parameters that you can send to it, and it also may or
may not return a value. We like to give descriptive names to our functions so
that we can infer what action they may provide us. Functions are the movers
and shakers in PHP, they are the main piece of getting your software to actually
do something. In this post we’ll take a closer look at User Defined Functions ,
Arguments to Functions , Returning Values from a Function, Recursive
Functions, as well as Variable Functions. We have a lot to cover so let’s jump
right in!

User Defined Functions


PHP has loads of built in functions and sometimes it seems overwhelming where to even
begin. Thankfully we already covered the most used php string functions as well as
the most used php array functions. Reading up on those will get you going with the key
built in functions of the language. Right now we’re going to talk about making our very own
functions for our special case use.
The syntax for creating a function is very easy. Let’s check it out:
<?php

function function_name() {
// do stuff
}

The naming of the function is any string beginning with a letter or underscore followed by a
combination of digits, letters, or underscores. Make it easy on yourself and choose simple
descriptive naming for your functions, no need to get fancy. PHP functions are not case
sensitive however it is best practice to always use all lowercase letters. Though they don’t
have to, functions will usually return a value. This is done using the keyword return, and
any number of return statements can be used in the function in condition checking
scenarios. Once the return keyword is reached in the program, control goes back to the
calling code along with the value produced by the expression in the function. For example:
<?php
function br() {
echo '<br>';
// optional return statement
}
function add($num1, $num2) {
return $num1 + $num2;
// returning a value
}

echo add(5, 4); // 9


br(); // <br>
echo add(4, 3); // 7
?>

Arguments to Functions
Functions can accept a certain number of arguments by declaring them in the function
definition. There are two different ways to pass parameters to a function and we’ll take a
look at them now.

Passing by value
Usually parameters are passed by value in PHP, but you also have the option of passing
by reference. The argument in the function is any valid expression which when evaluated
assigns the value to the variable in the function.
<?php
function doublefail($value) {
$value = $value * 2; // when this line runs $c retains 4
}
$c = 4;
doublefail($c);
echo $c; // 4

function doublefailreturn($value) {
return $value = $value * 2;
}
$d = 10;
echo doublefailreturn($d); // returns 20
echo $d; // leaves $d set to 10
?>
In the doublefail function, we use pass by value, so when the function runs, it doubles
the copy of the variable, not the value of the caller’s variable like the doubleitfunction
does. You could get what you want out of doublefail if you return the copy like in the last
example.

Passing by Reference
You can override the scoping rules and have the function gain direct access to a variable
by using pass by reference. To do this, you add an ampersand & to the front of the variable
name in the parameter list.
<?php
function doubleit(&$value) {
$value = $value * 2; // when this line runs $b gets set to 8
}
$b = 4;
doubleit($b);
echo $b; // 8
doubleit(7); // Fatal error: Only variables can be passed by reference
?>

The doubleit function passes $value by reference, that is to say the actual value
of $b instead of a copy of said value. This allows the function to modify the value directly
and when we then echo out the value, we see it gets doubled from 4 to 8 successfully.
Only variables can be supplied to parameters declared as passing by reference.

Variable Length Argument Lists


A function may need a variable number of arguments. To declare a function with a variable
number of arguments, you leave out the parameter block entirely like this:
<?php

function awesomeFunction() {
// do awesome stuff
}

PHP gives you three functions to use in the function in order to get the parameters passed
to it.
func_get_args() returns an array of all parameters provided to a function;
func_num_args() returns the number of parameters provided to a function;
func_get_arg() returns a specific argument from the parameter list.
For example:
<?php

$array = func_get_args();
$count = func_num_args();
$value = func_get_arg(argument_index);

In the following example, the add_arguments_lis() function takes in any number of


arguments. It then loops over those arguments, adds to the total on each iteration, and
returns the sum of all the values once complete. If no parameters are given, it will simply
return false.
<?php
function add_arguments_list() {
if(func_num_args() == 0) {
return false;
} else {
$count = 0;
for($i = 0; $i < func_num_args(); $i++) {
$count += func_get_arg($i);
}
return $count;
}
}
echo add_arguments_list(25, 50, 75); // outputs "150"
?>

These functions cannot be directly used as a parameter to another function. You must first
set a variable to the result of the function, and then use that in the function call.

Returning Values from a Function


PHP functions return only a single value with the return keyword:
<?php

function returnIt() {
return 'It';
}

If you would like to return multiple values, we need to return an array:


<?php

function returnArray() {
return array("Tom", 37, "Music");
}

or return an object:
<?php

class User {
public $userid;
public $name;
public $status;
}

function GetUser($userid) {
$userObj = new User();
$userObj->userid = $userid;
$userObj->name = 'Rick James';
$userObj->status = 'Super Freak';
return $userObj;
}

$newuser = GetUser(1);
var_dump($newuser);
?>

If no return value is provided by a function, the function returns NULL.

Recursive Functions
A recursive function is a function that calls itself. Recursion sounds straightforward, but
once you start working with it and try to really understand how it works, it can be very
tricky.
To write a recursive function, you need to provide it with some means of return or else it
will keep calling itself until the program crashes. This is known as the base case. The base
case is often found in a conditional like an if statement that will stop the recursion once a
condition is met. You also need a recursive case. This is where the recursion, or looping if
you will, takes place. The function is called on itself using the recursive case.

Factorials
The textbook example of recursion is the factorial example. The factorial function
symbol(!) means to multiply a series of descending non negative numbers like so:
4! = 4 × 3 × 2 × 1 = 24
7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040
8! = 8 x 7 × 6 × 5 × 4 × 3 × 2 × 1 = 40320
Instead of manually doing this math, we could create a function that accepts a number,
and then calculates the factorial by recursion:
<?php

function factorial($number) {

if ($number < 2) {
return 1; // base case
} else {
return ($number * factorial($number-1)); // recursive case
}
}

factorial(4);

Many tutorials leave out the fact that this comes from the formula n! = n × (n-1)!which
means “the factorial of any number is that number times the factorial of (1 smaller than
that number)”
We’ll go step by step through this function using the number 4 to keep it manageable. To
do this I have put the code above into eclipse pdt and will step into each execution step.
1. The function definition gets read into memory
2. factorial(4); is called.
3. $number is now 4 so we move to the else clause
4. Recursion! The function calls itself passing in 3 as it’s parameter
5. $number is now 3 so we move to the else clause
6. Recursion! The function calls itself passing in 2 as it’s parameter
7. $number is now 2 so we move to the else clause
8. Recursion! The function calls itself passing in 1 as it’s parameter
9. $number is now 1 so we return 1
10. echo factorial(4); now outputs the answer of 24.

Variable Functions
Variable functions will be useful when we cover object oriented programming. In the mean
time we’ll look at the basics of how variable functions work. A variable function is simply
where you assign a function name to a variable and then you can call that function by
using the variable name.
Let’s remember our example of the factorial function. We could create a random variable
name and assign that function to it using the following syntax:
<?php

$fact = 'factorial';
//We can then call that function like so
echo $fact(5); //120

Note that language constructs such as echo() and isset() cannot be called through
variable functions:
<?php

$variable = "echo";
$variable("hello, world"); // does not work
Now that we have a good grip on functions in PHP, let’s whip up some PHP String Helper
Functions to help with common string manipulation tasks!
PHP is incredibly powerful right out of the box, even if you aren’t using any
frameworks. We need to be fluent with the language itself as well as the
frameworks we might like to use. Using the built in functions of the language we
can create our own functions, or wrapper functions, of the built in ones.
Sometimes this helps with just being able to more closely match your desired
workflow. In this example we are going to create some String Helper functions
to use that will help us to quickly work on strings in a very easy way. We’ll make
use of 6 built in PHP functions, those being, strtolower, strpos, substr, strlen,
preg_match_all, and str_replace, to build 4 new string helper functions. Let’s do
it!

Initial Configuration
Let’s first define some constants so that we can use these values in the helper functions.
<?php

// Include or exclude the setpoint


define ( "EXCL", true );
define ( "INCL", false );
// Get text before or after the setpoint
define ( "BEFORE", true );
define ( "AFTER", false );

split_string()
First up is the split_string() function. It allows us to break a string into two pieces based
on a setpoint, and then grab either side of the two pieces with or without the setpoint. It
uses the built in PHP functions strtolower, strpos, and substr.
<?php

// Splits a string on a given setpoint, then returns what is before


// or after the setpoint. You can include or exclude the setpoint.
function split_string($string, $setpoint, $beforaft, $incorexc) {
$lowercasestring = strtolower ( $string );
$marker = strtolower ( $setpoint );

if ($beforaft == BEFORE) { // Return text BEFORE the setpoint


if ($incorexc == EXCL) {
// Return text without the setpoint
$split_here = strpos ( $lowercasestring, $marker );
} else {
// Return text and include the setpoint
$split_here = strpos ( $lowercasestring, $marker ) + strlen ( $marker );
}
$result_string = substr ( $string, 0, $split_here );
} else { // Return text AFTER the setpoint
if ($incorexc == EXCL) {
// Return text without the setpoint
$split_here = strpos ( $lowercasestring, $marker ) + strlen ( $marker );
} else {
// Return text and include the setpoint
$split_here = strpos ( $lowercasestring, $marker );
}
$result_string = substr ( $string, $split_here, strlen ( $string ) );
}
return $result_string;
}

find_between()
Next up is the find_between() helper function. This handy guy basically just makes use of
the split_string() function to help us to find a substring that is between a start and end
point that we give it.
<?php

// Finds a string between a given start and end point. You can include
// or exclude the start and end point
function find_between($string, $start, $stop, $incorexc) {
$temp = split_string ( $string, $start, AFTER, $incorexc );
return split_string ( $temp, $stop, BEFORE, $incorexc );
}

find_all()
Now we come to the find_all() function which is very useful. It makes use of the very
popular preg_match_all() function to find all occurrences of a pattern in between a starting
and ending delimiter. The real meat of this one is the pattern that gets passed
into preg_match_all(). We can see the first argument is the pattern consisting
of "($start(.*)$end)siU". This takes our start point, captures anything and everything
multiple times(.*), denoted by the dot and asterisk operators, stops at the end point,
performs a case insensitive match (i), excludes line breaks (s), and is not greedy (U).
These modifiers are extremely important for the RegEx to work properly.
<?php

// Uses a regular expression to find everything between a start


// and end point.
function find_all($string, $start, $end) {
preg_match_all ( "($start(.*)$end)siU", $string, $matching_data );
return $matching_data [0];
}

delete()
The delete() function is useful for removing one, or many substrings from within a string.
We simply pass it a string, a start point, and an end point, and the function will take care of
the rest for us!
<?php

// Uses str_replace to remove any unwanted substrings in a string


// Includes the start and end
function delete($string, $start, $end) {
// Get array of things that should be deleted from the input string
$delete_array = find_all ( $string, $start, $end );

// delete each occurrence of each array element from string;


for($i = 0; $i < count ( $delete_array ); $i ++)
$string = str_replace ( $delete_array, "", $string );

return $string;
}

Using Our New Helper Functions


Ok, we now have our helper functions defined, but how do we use them? Well, we can
create a file called Stringhelpers.php and dump all of the code into it just like this:
<?php
// string helper functions

// Include or exclude the setpoint


define ( "EXCL", true );
define ( "INCL", false );
// Get text before or after the setpoint
define ( "BEFORE", true );
define ( "AFTER", false );

// Splits a string on a given setpoint, then returns what is before


// or after the setpoint. You can include or exclude the setpoint.
function split_string($string, $setpoint, $beforaft, $incorexc) {
$lowercasestring = strtolower ( $string );
$marker = strtolower ( $setpoint );

if ($beforaft == BEFORE) { // Return text BEFORE the setpoint


if ($incorexc == EXCL) {
// Return text without the setpoint
$split_here = strpos ( $lowercasestring, $marker );
} else {
// Return text and include the setpoint
$split_here = strpos ( $lowercasestring, $marker ) + strlen ( $marker );
}
$result_string = substr ( $string, 0, $split_here );
} else { // Return text AFTER the setpoint
if ($incorexc == EXCL) {
// Return text without the setpoint
$split_here = strpos ( $lowercasestring, $marker ) + strlen ( $marker );
} else {
// Return text and include the setpoint
$split_here = strpos ( $lowercasestring, $marker );
}
$result_string = substr ( $string, $split_here, strlen ( $string ) );
}
return $result_string;
}

// Finds a string between a given start and end point. You can include
// or exclude the start and end point
function find_between($string, $start, $stop, $incorexc) {
$temp = split_string ( $string, $start, AFTER, $incorexc );
return split_string ( $temp, $stop, BEFORE, $incorexc );
}

// Uses a regular expression to find everything between a start


// and end point.
function find_all($string, $start, $end) {
preg_match_all ( "($start(.*)$end)siU", $string, $matching_data );
return $matching_data [0];
}

// Uses str_replace to remove any unwanted substrings in a string


// Includes the start and end
function delete($string, $start, $end) {
// Get array of things that should be deleted from the input string
$delete_array = find_all ( $string, $start, $end );

// delete each occurrence of each array element from string;


for($i = 0; $i < count ( $delete_array ); $i ++)
$string = str_replace ( $delete_array, "", $string );

return $string;
}

Now when we want to use any of these functions we can simply include this file like so:
<?php
include('Stringhelpers.php');
and we will have access to our new functions! Let’s test it out. We’ll create a new file
called stringtest.php, include our helper file, and just call each new function on a small
piece of text. Let’s see the results:
<?php
include('Stringhelpers.php');

$string = 'One really awesome string';

echo split_string($string, 'awesome', BEFORE, INCL);


// One really awesome

echo split_string($string, 'awesome', AFTER, EXCL);


// string

echo find_between($string, 'One', 'string', EXCL);


// really awesome

echo find_between($string, 'really', 'string', INCL);


// really awesome string

$string = 'One really awesome string. Two really awesome strings!';


print_r(find_all($string, 'really', 'string'));
// Array ( [0] => really awesome string [1] => really awesome string )

$string = 'Why do silly, green, or yellow frogs jump? Why do silly, green, or yellow frogs jump?';

echo delete($string, 'silly', 'yellow');


// Why do frogs jump? Why do frogs jump?
?>

Wow! That was really cool! Now what’s the big deal with all this Laravel we’ve been talking
about, then shifting gears and creating some simple PHP string helper functions?! Listen
now Grasshopper, there is a method to our madness! You see before frameworks, this is
how we did things. We created functions, we put them in files, we included those files into
other files, and tada!, WordPress was born. Just kidding – but in all seriousness, we all
probably have a lot of great functions and snippets of code in our arsenal. Once we start
using a great framework like Laravel, do we have to abandon those old functions that
we’ve come to know and love? But of course not! Now that we have created a file
containing a handful of helper functions, we will have something to work with for our next
tutorial. In our next episode, we’ll take a look at how to convert our old file based functions,
and put them into a dedicated class which can be added to a libraries folder in Laravel.
Then we’ll set up autoloading of any libraries we want to add to our project, and we’ll be
able to use the new hotness of Laravel, along with any of our own Library functions we’ve
collected over the years!

The Ultimate Guide to PHP Functions


Functions are what make our code tick. At the end of the day, we’d like our
code to actually do something. The function is what makes this happen, it is the
verb, the call to action. The building blocks of all great programs are functions.
In PHP there are thousands of built in functions, along with the ability to define
your own. Since functions are so important to our everyday programming, this
tutorial will serve as the ultimate guide to PHP functions. Let’s jump in!

When we program, we need to find a balance between procedure and abstraction. The
function is the very beginnings of abstraction. When first setting out to solve a problem, we
may not even know how we are going to complete the task. At this early stage, it makes
sense to attack the problem with carefully planned steps or procedures. Once we have a
workable solution in place, we can put those procedures into a block of code, and create a
function with it. A function is this named block of code. It should perform a specific job,
and may accept parameters, also called arguments, given to it to perform it’s task. The
function will usually return a value. Functions make our code more efficient, and also
provide the benefit of saving on compile time. The reason being is that even if we call our
function 10 times within a page, it is compiled only once. Another benefit is that, if you
need to fix a bug or change logic within it, once it is updated in this one place, all other
function calls on this function, whether it be 10 or 100 other instances, will now work
correctly. It’s better to update code in one spot versus 100! Lastly, functions help make our
code more readable, especially if we give them meaningful names, and isolate their job to
a specific task.

We’ll take a close look at the syntax of defining functions, as well as the syntax of calling
both built in, and user defined functions.
Call a Function in PHP
No matter if a function was created by you, the awesome programmer, or if the function is
already a built in to the language, it will be evaluated in the same way.
$returnvalue = $named_function( [ parameter, ... ] );
A function might accept no parameters at all, or several parameters. Each function is
different. The parameters given to the function must be in a specific order, and can be any
valid expression, so long as it meets the expectations of the function definition. Passing in
parameters that are out of order can result in anything from unexpected results, to a full
fledged program crash. By reading the documentation of a function, you will know what it
expects.

Examples of Functions
array_unique()
array_unique() is a built in function that removes duplicate entries in an array
<?php

$languages = array( 'php', 'php', 'javascript', 'javascript', 'ruby' );


$unique = array_unique( $languages );

var_dump($unique);
array (size=3)
0 => string 'php' (length=3)
2 => string 'javascript' (length=10)
4 => string 'ruby' (length=4)

substr()
substr() is a built in function that allows you to find a substring within a string.
<?php
$gaming = substr("Playstation ".strlen('four')." is incredibly awesome!", 4, -1);
var_dump($gaming);
string 'station 4 is incredibly awesome' (length=31)

array_unshift()
array_unshift() is a built in function that allows you to add a value to the very beginning
of an array.
<?php

$legocharacters = array( 'Emmet', 'Vitruvius', 'Ma Cop', 'Pa Cop', 'Lord Business', 'El Macho');
array_unshift( $legocharacters, 'Biznis Kitty' );
var_dump($legocharacters);

array (size=7)
0 => string 'Biznis Kitty' (length=12)
1 => string 'Emmet' (length=5)
2 => string 'Vitruvius' (length=9)
3 => string 'Ma Cop' (length=6)
4 => string 'Pa Cop' (length=6)
5 => string 'Lord Business' (length=13)
6 => string 'El Macho' (length=8)

We call a function by simply referencing it’s name. In the first example, an argument is
passed to the function array_unique(). This argument is an array, because that is what
the function expects to be given. We can see that the array_unique() function accepts an
array, removes any duplicates from it, and returns the unique array.
The second example also accepts an argument, but in this case it is of type string. You
can see in this example how we can call a function within a function. In this
example, strlen() is called within substr(). The returned value of the inner function gets
passed to the outter function and then the final result is returned.
Lastly, we make use of the array_unshift() function which takes two parameters, an
array, and a value to add to the array.
PHP has a lot of built in functions. Were talking on the order of 5000+ built in functions
available for your enjoyment. When starting out, it may be difficult to know where to start.
One thing that may help is to determine the most used functions in the language and start
there. Since strings and arrays are the most common data types used, it makes sense to
start with the most popular php string functions and the most popular array
functions. Memorizing this small collection is enough to get you up and running for some
basic programming, and help you to debug your various themes and plugins.

Define Your Own Functions


We can define our own functions using the function keyword. Let’s say I want a function
that makes it easier to dump the type and contents of a variable to the screen. Here is an
example of a function that does just that.
<?php

function dump ($value) {


var_dump($value);
}

$legocharacters = array( 'Emmet', 'Vitruvius', 'Ma Cop', 'Pa Cop', 'Lord Business', 'El Macho');

dump($legocharacters);

array (size=6)
0 => string 'Emmet' (length=5)
1 => string 'Vitruvius' (length=9)
2 => string 'Ma Cop' (length=6)
3 => string 'Pa Cop' (length=6)
4 => string 'Lord Business' (length=13)
5 => string 'El Macho' (length=8)

Let’s go over what is happening here. First we use the keyword function, this tell us that
the next piece of text is going to be the way we identify or name this block of code for
reuse. Second, we can see that the function expects a $value parameter to be passed in.
Note that you can assign any name you like to this parameter, it is simply an identifier for
what will be passed into the function when it get’s called. In this function, it is not optional,
we need this value passed in so the function will run without error. If we try to call
the dump() function with no parameters passed in, we will get a scary message that looks
like this:
Warning: Missing argument 1 for dump()
We can make a parameter optional by assigning it a value in the function declaration. Let’s
see what that would look like:
<?php

function dump ($value = 'Lord Business Evil Lair') {


var_dump($value);
}

Now, when we call the dump() function without passing in any arguments, it will not bark at
us! When the function is called, it will see that no argument was given, therefore it will
assign the provided text from the function declaration to $value, and use that inside the
function. On the other hand, if we call the dump() function and pass in a value, the function
will ignore the text of the function declaration, and work it’s magic on the value that we
pass in, just like when we passed an array of $legocharacters to it. By providing default
values to your parameters in the function declaration, you are making your functions
more flexible and useful.

Returning a Value
The example above did not return a value, but normally a function would. When we want to
return a value from a function, we will use the return keyword. The return statement goes
inside the code block of the function. In fact, you can have many return statements inside
the function, since you may have some logic or tests that will run, and a value will be
returned only when a specific case occurs. Once a return statement is hit during the
programs execution, control gets handed back to the calling statement along with the
return value. The return keyword can accept any expression, it is quite flexible. You
can return $a + $b ( 5 / $c ); just as easily as return $a;. As an example we could
have an add function set up like this:
<?php

function add ($num1, $num2) {


$sum = $num1 + $num2;
return $sum;
}

or we could clean things up and simply use this style:


<?php

function add ($num1, $num2) {


return $num1 + $num2;
}

Both of these examples would produce the same return value.


Let’s create another example of a user defined function. In this one we will work some
magic on arrays, and specifically we’ll create an array_pluck() function to give us the
ability to pluck values from an array:
<?php

$teachers = array(
array('name' => 'Jen', 'job' => 'teacher', 'grade' => 5),
array('name' => 'Sarah', 'job' => 'teacher', 'grade' => 3),
array('name' => 'Heather', 'job' => 'teacher', 'grade' => 6),
array('name' => 'Lynn', 'job' => 'teacher', 'grade' => 5)
);

function array_pluck($topluck, $arr){


$newarray = array();

foreach($arr as $item){
$newarray[] = $item[$topluck];
}

return $newarray;
}

$result = array_pluck('grade', $teachers);


print_r($result);

Array ( [0] => 5 [1] => 3 [2] => 6 [3] => 5 )

An array pluck function is very useful in many instances of web development. You may be
familiar with the MVC or Model View Controller pattern. When we use MVC and pass data
from controllers to views, usually the keys of the data array end up becoming the variable
names in the view. This is using the array pluck pattern to make this possible.
We can refactor the first iteration of our array_pluck() function using the built
in array_map() function. This will also help us see the return statement in a different light,
as well as highlight variable scope in php functions.
<?php
function array_pluck($topluck, $arr){
return array_map(function($item) use($topluck) {
return $item[$topluck];
}, $arr);
}

$result = array_pluck('name', $teachers);


print_r($result);

Array ( [0] => Jen [1] => Sarah [2] => Heather [3] => Lynn )

Awesome! As we can see this second iteration works just as well. Note that the return
statement is returning a complex expression in this example like we mentioned earlier.
Now wait a minute, what is that use($topluck) business all about? Well in PHP, a function
uses local scope, also called function level scope. This means that functions keep their
own sets of variables that are distinct from any others on the page and also of any other
functions. Variables in one function do not have access to variables in another function
and vice versa. The variables defined inside a function, including its parameter list, are not
available outside the function, and, by default, variables defined outside a function are not
accessible inside the function. How do we get around this?

Closures and Anonymous Functions


We can see that the array_map() function inside of the array_pluck() function accepts a
nameless function as it’s first parameter. What?! That’s right, not only can you pass a
function to a function, you can pass a function that has no name to a function. This is
called an anonymous function. In addition to the anonymous function, we specify use of
a closure with the use($topluck) construct. Without this, the inner function would not have
access to the variables of the outer function, and the function would fail.

Pass by Value vs Pass by Reference


Pass by Value
It is much more common to pass by value than by reference in PHP, but you but there are
times when you will need to pass by reference. We’ll show this by creating two versions of
a function that should double a value passed in.
<?php

function double($value) {
$value = $value * 2;
}
$number = 4;

double($number);
echo $number; // 4
This code is using pass by value, which means a copy of the variable is passed in.
Therefore when the function runs, it doubles the copy of the variable, not the value of the
caller’s variable. Fear not! We can fix this

Pass by Reference
We are going to do something drastic. We will entirely rewrite the function and use pass by
reference now:
<?php

function double(&$value) {
$value = $value * 2;
}

$number = 4;
double($number);

echo $number; // 8
?>

Yes it is working, and you’ll notice all we did was add the & operator to
Hey, it’s working now!
the parameter in the function declaration. This works because a copy is never made in
this case, the variable simply gets passed in. You can almost think of it like a pointer to a
memory address. Note that only variables can be supplied to parameters declared as
passing by reference. In addition, there is no reference sign on a function call – only on the
function definition. Function definitions alone are enough to correctly pass the argument by
reference.

Conclusion
We covered a lot in this PHP function tutorial. If you’re in the beginning stages of your PHP
journey, read this post many times until the concepts are second nature to you. If you’re
already an advanced code slinger, hopefully you found some nice refreshers in this post as
well. What’s next? Consider jumping into Object Oriented PHP!

The 27 Most Popular File Functions in PHP


After getting a firm grasp on PHP Strings and PHP Arrays, the next good stop
for your mastery is working with files and the filesystem. Because PHP so
easily integrates with all kinds of database connectivity, many times folks will
overlook plain old flat files for methods of storage and caching. Working with
the files and the filesystem however, can be extremely efficient, especially for
small projects or applications. So without further ado, let’s dig into the 27 Most
Popular File Functions in PHP!

file_exists()
bool file_exists(string path)
Returns true if the file at path exists and false if not.
file_exists() is used to check if a file, wait for it, exists!
If you want to see if a file exists without actually opening it, you can use file_exists()like
so:
<?php

if (file_exists("jobsinqueue.txt")) {
echo 'There are jobs in the queue waiting to be processed.';
} else {
echo 'There are currently no jobs in the queue.';
}
is_file()
bool is_file(string path)
is_file returns true if path exists and is a file, otherwise it returns false.
<?php

var_dump(is_file('atextfile.txt')); // true
var_dump(is_file('/app/blog/')); // false

is_readable()
bool is_readable(string path)
is_readable returns true if path exists and is readable, otherwise it returns false.
<?php

$filename = 'thefile.txt';
if (is_readable($filename)) {
echo 'The file is readable!';
} else {
echo 'The file is not readable';
}

is_writable()
bool is_writable(string path)
is_writable returns true if path exists and is a directory, otherwise it returns false.
<?php

$filename = 'writetome.txt';
if (is_writable($filename)) {
echo 'We can write to the file!';
} else {
echo 'Sorry, this file is not writable.';
}
filesize()
int filesize(string path)
You can check the size of a file by using the filesize() function. filesize returns the size
of a file in bytes and can be used in conjunction with fread() to read a whole file (or just a
part of the file) at a time. If the file does not exist or any other error occurs, the function
returns false.

fopen()
resource fopen(string path, string mode[, bool include [, resource context ]] )
fopen opens the file specified by path and returns a file resource handle to the open file. If
path begins with http://, an HTTP connection is opened and a file pointer to the start of
the response is returned. If path begins with ftp://, an FTP connection is opened and a
file pointer to the start of the file is returned; the remote server must support passive FTP.
If path is php://stdin, php://stdout, or php://stderr, a file pointer to the appropriate
stream is returned. Be aware of the different options with fopen()

ModeName Meaning
r Read Open the file for reading, beginning from the start of the file.

r+ Read Open the file for reading and writing, beginning from the start of the file.

Open the file for writing, beginning from the start of the file. If the file already exists, delete the existing
w Write
contents. If it does not exist, try to create it.

Open the file for writing and reading, beginning from the start of the file. If the file already exists, delete the
w+ Write
existing contents. If it does not exist, try to create it.

Cautious Open the file for writing, beginning from the start of the file. If the file already exists, it will not be
x
write opened, fopen() will return false, and PHP will generate a warning.

Cautious Open the file for writing and reading, beginning from the start of the file. If the file already exists, it will not be
x+
write opened, fopen() will return false, and PHP will generate a warning.

Open the file for appending (writing) only, starting from the end of the existing contents, if any. If it does not
a Append
exist, try to create it.

Open the file for appending (writing) and reading, starting from the end of the existing contents, if any. If it does
a+ Append
not exist, try to create it.

Used in conjunction with one of the other modes.You might want to use this mode if your file system
b Binary differentiates between binary and text files.Windows systems differentiate; Unix systems do not.The PHP
developers recommend you always use this option for maximum portability. It is the default mode.

Used in conjunction with one of the other modes.This mode is an option only in Windows systems. It is not
t Text
recommended except before you have ported your code to work with the b option.
ftell()
int ftell(resource handle)
ftell returns how far into the file the pointer is in bytes. If an error occurs, it returns false.
<?php

$fp = fopen("composer.json", "r");


$data = fgets($fp, 2);

// where are we ?
echo ftell($fp); // 1

fclose($fp);

fwrite() alias is fputs()


int fwrite(resource handle, string string[, int length])
fwrite writes string to the file referenced by handle. The file must be open with write
privileges. If length is given, only that many bytes of the string will be written. Returns the
number of bytes written, or −1 on error.
Writing to a file in PHP is fairly easy. You can use either of the functions fwrite() (file
write) or fputs() (file put string). fputs() is an alias to fwrite(). I’m not sure why there are
functions named differently but do the same thing in PHP, but we do have these alias
functions at times. You call fwrite() in the following way:
<?php

$fp = fopen("text.txt", "w");

fwrite($fp, 'Some awesome text!');

readfile('text.txt'); // Some awesome text!

fclose()
bool fclose(int handle)
After you’ve finished using a file, you should close it as a best practice with fclose. You
should do this by using the fclose() function as follows:
<?php

fclose($fp);
This function returns true if the file was successfully closed or false if it was not.

fread() alias is fgets()


string fread(int handle, int length)
You can use the fread() function to read an arbitrary number of bytes from the
file.fread reads up to length bytes, to the end of the file or network packet, whichever
comes first.
<?php

$filename = "text.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

var_dump($contents); // string 'Some awesome text!' (length=18)

file_get_contents()
string file_get_contents ( string $filename [, bool $use_include_path = false [,
resource $context [, int $offset = -1 [, int $maxlen ]]]] )
file_get_contents is an incredibly powerful function, file_get_contents() reads the file at
path and returns its contents as a string, optionally starting at offset. If include is specified
and is true, the include path is searched for the file. The length of the returned string can
also be controlled with the maxlen parameter.
<?php

$contents = file_get_contents('text.txt');
echo $contents; // Some awesome text!

file_put_contents()
int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [,
resource $context ]] )
A close cousin of the file_get_contents() function and an alternative to fwrite() is
the file_put_contents() function. file_put_contents makes your life easy and writes the
string contained in data to the file named in filename without any need for
an fopen() (or fclose()) function call! Returns the number of bytes written to the file, or −1
on error. The flags argument is a bitfield with two possible values:
FILE_USE_INCLUDE_PATH If specified, the include path is searched for the file and the
file is written at the first location where the file already exists.
FILE_APPEND If specified and if the file specified by path already exists, string is
appended to the existing contents of the file.
LOCK_EX Exclusively lock the file before writing to it. Useful for preventing race conditions
during file writing.
<?php

$contents = 'The most awesome text yet!';


file_put_contents('text.txt', $contents);

readfile('text.txt'); // The most awesome text yet!

file()
array file(string filename[, int flags [, resource context ]])
This handy function works a lot like readfile() except that instead of echoing the file to
standard output, it turns it into an array. Each key of the array contains one line of the file.
Flags can be one or more of the following constants when using the file function:
FILE_USE_INCLUDE_PATH Search for the file in the include path as set in the php.ini
file.
FILE_IGNORE_NEW_LINES Do not add a newline at the end of the array elements.
FILE_SKIP_EMPTY_LINES Skip any empty lines.
We have modified our text.txt file for an example and placed several lines of text on new
lines. Now you can see how the file() function reads the text in, and assembles an array:
<?php

$contents = file('text.txt');
print_r($contents);

Array
(
[0] => The most awesome text yet!

[1] => This is line 2.

[2] => This is line number 3.

[3] => You guessed it, you have reached line 4!


)
glob()
array glob ( string $pattern [, int $flags = 0 ] )
glob returns a list of filenames matching the shell wildcard pattern given in pattern. The
following characters and sequences make matches:
* Matches any number of any character (equivalent to the regex pattern .*)
? Matches any one character (equivalent to the regex pattern .)
For example, to process every JPEG file in a particular directory, you might write:
<?php

foreach(glob("/tmp/images/*.jpg") as $filename) {
// do something with $filename
}

The flags value is a bitwise OR of any of the following values:


GLOB_MARK Adds a slash to each item returned.
GLOB_NOSORT Returns files in the same order as found in the directory itself. If this is
not specified, the names are sorted by ASCII value.
GLOB_NOCHECK If no files matching pattern are found, pattern is returned.
GLOB_NOESCAPE Treat backslashes in pattern as backslashes, rather than as the start
of an escape sequence.
GLOB_BRACE In addition to the normal matches, strings in the form {foo, bar,
baz}match either “foo”, “bar”, or “baz”.
GLOB_ONLYDIR Returns only directories matching pattern.
GLOB_ERR Stop on read errors.

basename()
string basename ( string $path [, string $suffix ] )
The basename() function gets the name of the file without the directory.
For example we could use basename like this:
<?php

$path = "/usr/local/httpd/index.html";

echo(basename($path)); // index.html
echo(basename($path, '.html')); // index
dirname()
string dirname ( string $path )
The dirname() function gets the directory name without the filename. dirname includes
everything up to the filename portion and doesn’t include the trailing path separator.
<?php

// get the current directory


$dir = dirname(__FILE__);
echo $dir; // C:wampwwwphpconsole

pathinfo()
mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME |
PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )
pathinfo returns an associative array containing information about path. If the options
parameter is given, it specifies a particular element to be
returned. PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION,
and PATHINFO_FILENAME are valid options values.
<?php

$array = pathinfo('krumo/krumo.js');
print_r($array);

Array
(
[dirname] => krumo
[basename] => krumo.js
[extension] => js
[filename] => krumo
)

realpath()
string realpath ( string $path )
realpath expands all symbolic links, resolves references to /./ and /../, removes
extra / characters in path, and returns the result.
<?php

$string = realpath('krumo/krumo.js');
echo $string; // C:wampwwwphpconsolekrumokrumo.js

unlink()
bool unlink ( string $filename [, resource $context ] )
unlink deletes the file path, using the streams context context if provided. Returns true if
the operation was successful and false if not. This situation typically occurs if the
permissions on the file are insufficient or if the file does not exist.
<?php

unlink('text.txt');

readfile('text.txt'); // error no such file exists! (we just deleted it)

rename()
bool rename(string old, string new[, resource context]))
The rename() function does double duty as a function to move files from place to place
since PHP does not include a move function. Whether you can move files from file system
to file system and whether files are overwritten when rename is used will likely depend on
your server environment, so be sure to check the effects on your server.
<?php

rename('text.txt', 'newtext.txt'); // text.txt is now newtext.txt

rename('newtext.txt', 'krumo/inKrumoDirectoryNow.txt');
// newtext.txt is now moved and renamed in one shot
// newtext.txt no longer exists in the original directory!

copy()
int copy(string path, string destination[, resource context ])
copy copies the file at path to destination. If the operation succeeds, the function
returns true, otherwise it returns false. If the file at the destination exists, it will be
replaced. The optional context parameter can make use of a valid context resource
created with the stream_context_create() function.
<?php

copy('krumo/inKrumoDirectoryNow.txt', 'copied.txt');
// copied.txt is now in the destination directory
// inKrumoDirectoryNow.txt still exists in the source directory

filemtime()
int filemtime(string path)
filemtime returns the last-modified time, as a Unix timestamp value, for the file path.
<?php

$modified = filemtime('copied.txt');

echo $modified; // 1395861849

is_dir()
bool is_dir(string path)
is_dir returns true if path exists and is a directory, otherwise it returns false.

mkdir()
bool mkdir(string path[, int mode [, bool recursive [, resource context ]]])
mkdir creates the directory path with mode permissions. The mode is expected to be an
octal number such as 0755. An integer value such as 755 or a string value such as “u+x”
will not work as expected. Returns true if the operation was successful and false if not. If
recursive is used, it allows for the creation of nested directories.

opendir()
resource opendir(string path[, resource context])
opendir opens the directory path and returns a directory handle for the path that is
suitable for use in subsequent readdir(), rewinddir(), and closedir() calls. If path is not
a valid directory, if permissions do not allow the PHP process to read the directory, or if
any other error occurs, false is returned. Its use is similar to the use of fopen() for reading
from files. Instead of passing it a filename, you should pass it a directory name. The
function returns a directory handle, again in much the same way as fopen() returns a file
handle. When the directory is open, you can read a filename from it by
calling readdir($dir), as shown in the example. This function returns falsewhen there are
no more files to be read. Note that it will also return false if it reads a file called 0; in order
to guard against this, we can explicitly test to make sure the return value is not equal
to false:
<?php

$dir = opendir($current_dir);
while(false !== ($file = readdir($dir))) {
// do stuff
}

When you are finished reading from a directory, you call closedir($dir) to finish. This is
again similar to calling fclose() for a file.

readdir()
string readdir([resource handle])
readdir returns the name of the next file in the directory referenced by handle. If not
specified, handle defaults to the last directory handle resource returned by opendir(). The
order in which files in a directory are returned by calls to readdir() is undefined. If there
are no more files in the directory to return, readdir() returns false.

chmod()
bool chmod(string path, int mode)
chmod attempts to change the permissions of path to mode. The mode is expected to be
an octal number, such as 0755. An integer value such as 755 or a string value such as
“u+x” will not work as expected. Returns true if the operation was successful and false if
not.

Create A File Class


Now that we have an overview of many of the most used file functions in PHP, we can
create a file class! Some of the file functions may seem a bit cryptic in their syntax, but by
creating a file class, we can give our methods more meaningful names which can lead to
more elegant and readable code. We’ll create a class that uses very simple static methods
to wrap existing PHP file functions to make them easier to use. Place this code into a file
called fileclass.php
<?php
class File {
public static function put($file, $data, $append = false) {
if ( $append ) {
return file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
}
return file_put_contents($file, $data, LOCK_EX);
}

public static function exists($file) {


return file_exists($file);
}

public static function read($file) {


return readfile($file);
}

public static function size($file) {


return filesize($file);
}

public static function name($file) {


return pathinfo($file, PATHINFO_FILENAME);
}

public static function extension($file) {


return pathinfo($file, PATHINFO_EXTENSION);
}

public static function last_updated($file) {


return filemtime($file);
}

public static function get($file) {


return static::exists($file)
? file_get_contents($file)
: false;
}

public static function append($file, $data) {


return static::put($file, $data, true);
}

public static function clear($file) {


if ( static::exists($file) ) {
$fp = fopen($file, 'w');
fclose($fp);
}
}

public static function delete($file) {


return unlink($file);
}
}

Awesome! Now you can easily make use of this class like so:
<?php

include('fileclass.php');

File::put('newfile.txt', 'The first file created with our file class!'); // create a new file

echo File::exists('newfile.txt'); // 1 or true

File::read('newfile.txt'); // The first file created with our file class!

echo File::size('newfile.txt'); // 43

echo File::name('newfile.txt'); // newfile

echo File::extension('newfile.txt'); // txt

echo File::last_updated('newfile.txt'); // 1395865958

echo File::get('krumo/inKrumoDirectoryNow.txt'); // yes, this file is in the krumo directory

File::append('newfile.txt', ' NEW DATA!');

File::read('newfile.txt'); // The first file created with our file class! NEW DATA!

File::clear('newfile.txt');

File::read('newfile.txt'); // file is now empty

File::delete('newfile.txt'); // file is now deleted

Conclusion
This was a fantastic crash course on the most popular file functions used in PHP. Learning
and memorizing the functions in this tutorial will take us a long way in sharpening our
programming chops.

The Ultimate Guide To Object Oriented PHP


PHP is now a mature language that has very strong support for object oriented
programming. We like to talk about frameworks a lot, and these frameworks are
built using object oriented PHP. In order for us to make the very best use of
these wonderful programming frameworks, we must have a very strong grasp
of object oriented techniques and best practices. The benefits are many, but at
the top of the list are much greater code reuse, clean design, and simplified
code maintenance. Let’s dig into object oriented PHP!

All About Objects


The Terms To Know For Your OOP Journey
One thing about OOP in PHP is that the verbiage is insane. We’re talking jargon like
you’ve never seen, but in reality, the concepts are fairly straightforward – the terms just
make them sound like rocket science. Fear not however, as rocket science is not a
prerequisite to learning object oriented php! In order to set the stage for our object oriented
journey, let’s first get the terms outlined.

Class:
It all starts with the class. The class is the master plan, dare I say the cliche but true,
blueprint, for your code. I like master plan though, it sounds a little more grand. In basic
terms, the class is a template or outline for creating objects.

Object:
The object comes from the class, much like a house would be built using a blueprint. We
call an object an instance of the class. One class can have many instances. Let’s say we
have a Person Class. As you know, we can have many people. At last count, I think there
are about 7 with a B, Billion of us on the planet. That’s a lot of objects coming from the
master class

Properties:
Objects have variables to store and manipulate data, but in OOP, they are
called properties.

Methods:
Just as we have variables, we also have functions, but again in OOP, they go by a
different name, method.

Encapsulation:
Our methods and properties in the class have visibility. You have likely seen
the public, private, and protected keywords. When you see these, you know that the
code is implementing encapsulation, or determining what can, or can not be, accessed
from inside and outside the class. The key points to know are:

• Private: The private keyword is used to label a property or method as accessible


from inside the class only.
• Public: The public keyword is used to denote a property or method that can be
accessed anywhere, including outside of the class, or any classes that extend the
parent class.
• Protected: Last up, we have the protected keyword. Protected says that the
properties and methods of a class can be accessed and manipulated only by the
parent class, or classes that extend the parent class. We can learn more about
visibility in php at the official docs.

Inheritance:
Inheritance is what we love about object oriented php. Inheritance is where we are able to
have very powerful code reuse. A new class can extend the parent class and even add or
modify existing properties and methods. It’s like a child that inherits all of her parent’s
greatness, and adds her own as well! The original class gets named things like base
class, parent class, or superclass. The new class is called the subclass or derived
class.
Using inheritance makes it possible to build on existing generic classes. Using a general
base class, one could create more focused and complex child classes as the need
becomes apparent. By following this convention, frequent and repeating blocks of code
can be written once in the superclass, instead of over and over in different subclasses. It
may also help to better resemble real world relationships. A simple test to see if
inheritance could or should be used is to insert an “is a” between the classes. If it makes
sense, then you could likely use inheritance. For example the sentence, “A Teacher is a
Person”, makes sense. It could make sense for a Teacher subclass to inherit from a
Person superclass. Not all Persons are Teachers however, so a Person would not inherit
from a Teacher.

Instantiating an Object
It’s easy to create a new object to use in our PHP program. We make use of
the newkeyword following this format:
<?php

$object = new Class;

Let’s pretend we have a Car class already defined. In order to create


an object or instance of that Car class we could do this:
<?php

$car = new Car;

Depending on how the class was defined, we might be able to pass arguments during the
creation of an object. Let’s assume we can in this example so we can pass arguments like
so:
<?php

$car = new Car('Subaru', 2017);

This would create a new car object and store it in $car. We can now access the methods
and properties of the object using the arrow operator. The official name
is T_OBJECT_OPERATOR, however arrow operator is easier to remember since it looks
like an arrow ->!

Property and Method Access


Accessing the properties and methods of our class is easy using the -> operator like so:
<?php
$car->make; // Subaru
$car->year; // 2014
$car->accelerate(); // method call

We can also pass an argument to a method call. The method can also return a value just
like normal php functions:
<?php

$car->accelerate(75); // go 75 mph

As we mentioned in the terms section above, encapsulation allows us to set the methods
and properties to either public, private, or protected in the class definition. In addition to
this normal process of object creation, we can use what are called static methods and
properties. When you do this, the method is called on the class itself, not the created
object. Statics are somewhat frowned upon in the community, but they are great for quick
and dirty problem solving, and their syntax is very elegant. The example from our File
Class is very easy to read and use:
<?php

File::put('newfile.txt', 'The first file created with our file class!');

You may not want to build a whole application out of static methods and properties, but for
helper type classes, they make a great option.
Passed by Reference
Objects are passed by reference in PHP. This saves memory in the computer and
provides the ability to maintain state of the object. For example:
<?php

$car = new Car('Subaru', 2017);

$c = $car;

$car->setMake('Porche');

var_dump($c);

object(Car)[1]
public 'make' => string 'Porche' (length=6)
public 'year' => int 2017

Wow! Even though we called the setMake() method on the $car object, a var_dump
of $c shows that the make is changed to ‘Porche‘! This is because both $c and $car point
at the same object
To make a true copy you can use the __clone() method like so:
<?php

$car = new Car('Subaru', 2017);

$c = clone $car;

$car->setMake('Porche');

var_dump($c);

object(Car)[2]
public 'make' => string 'Subaru' (length=6)
public 'year' => int 2017

CoolNow we can see that a copy has been made and $car will contain Porche while $c will
contain Subaru!

Defining A Class
Using classes that have been created for us is quite easy. We simply use
the new keyword, instantiate some objects, and then we can enjoy all the methods and
properties that the developers created for us. A great example of this is when we create a
new object in one of the many great php frameworks. Defining our own classes is a little
more tricky! When we define a class, we determine a class name, class properties, and
class methods. Class names are case insensitive, though it’s best practice to capitalize
your class names. At a minimum we can declare a class like so:
<?php

class Classname {

If we include all available options to us when creating our classes, the syntax would look
like so.
class classname [ extends baseclass ] [ implements interfacename , [interfacename, ... ] ]
{
[ use traitname, [ traitname, ... ]; ]
[ visibility $property [ = value ]; ... ]
[ function functionname (args) {
// code
}
...
]
}

That’s a lot of info, so let’s go through them one by one.


Defining Methods
A method is simply a function defined inside of a class. We can follow all the guidelines of
creating regular functions then, like choosing a descriptive name, and using approved PHP
characters. Stay away from the double underscore when naming your own functions since
this has special meanings in the language, depending on the context.
$this is a special keyword in PHP and can be a little tricky. Basically, it is a reference to
the current object. We can see how $this is used in this class definition of a Car.
<?php

class Car {

public $make;
public $year;

function __construct($make, $year){


$this->make = $make;
$this->year = $year;
}

public function accelerate($number){


echo 'going '.$number.' miles per hour';
}

public function setMake($make){


$this->make = $make;
}

public function getMake() {


return $this->make;
}

public function getYear() {


return $this->year;
}

This shows how the setMake() method makes use of $this to access and set
the $make property of the current object. We can also declare a static method using
the static keyword, just remember when calling that method, you call it on the class, not
the object. Recall from our php file functions tutorial:
<?php

class File {
public static function put($file, $data, $append = false) {
if ( $append ) {
return file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
}
return file_put_contents($file, $data, LOCK_EX);
}
}

and the use case:


<?php

File::put('newfile.txt', 'What a great file this is!');

Note that we use the Scope Resolution Operator, or double colon, instead of the arrow
operator, which allows access to static, constant, and overridden methods or properties in
a class. The official name for the double colon operator is, get this, the Paamayim
Nekudotayim, for which I have no idea how to pronounce
We can lock down our methods by using the final keyword. This stops classes that
extend the parent class from overriding the method.
For example:
<?php

class Car
{
public $make;
final function getMake()
{
return $this->make;
}
}

class Hybrid extends Car


{
// syntax error
function getMake()
{
// do something
}
}

Setting the visibility of a method is easy by using any of the keywords public, private,
or protected. If you do not specify a visibility, the method will default to public. For
example if we set $make to private, we’ll now get a fatal error if we try to access it outside
of the class:
<?php

class Car {

private $make;
public $year;
function __construct($make, $year){
$this->make = $make;
$this->year = $year;
}

public function accelerate($number){


echo 'going '.$number.' miles per hour';
}

public function setMake($make){


$this->make = $make;
}

public function getMake() {


return $this->make;
}

public function getYear() {


return $this->year;
}

$car = new Car('Subaru', 2014);

$car->setMake('Porche');

echo $car->make; // fatal error

echo $car->getMake(); // Porche

We could however still set the private property and get access to the private property since
the methods we use to access it setMake() and getMake(), are public.
Pretty Cool!

Defining Properties
We’ve been defining properties all along in the examples so far. No doubt you’re used to
working with variables in your programs, well properties work the same way except they
are tied to an instance of an object. In order to get access to them, we need to use the
object. Declaring properties are optional, but certainly a best practice since it makes our
code much more readable. For the lazy among us, we could rewrite the Car class without
explicit property declaration like so and we can still set and get the make property:
<?php

class Car
{
function getMake()
{
return $this->make;
}

function setMake($make)
{
$this->make = $make;
}
}

$car = new Car;


$car->setMake('Honda');
echo $car->make; // Honda

You can also set default values to properties on declaration so long as those default
values are simple constants:
<?php

public $make = "Lexus"; // valid


public $year = 2013; // valid
public $speed = 60 * 2; // not valid

As you know, we have the option of declaring our properties to public, private, or
protected, based on how much visibility we would like to assign to them. We can also set
them to static and interact with them like so:
<?php

class Car
{
static $color = 'Blue';
}

$color = Car::$color;

Inside the object class, you can get access to the static property using the self keyword,
like so self::$color.
Getters and Setters
A key advantages of OOP is that it encourages encapsulation. This can be enforced with
the use of __get and __set functions. They may seem a little mundane, but the way these
get and set functions work is really cool! This allows you to access the class properties via
those methods rather than directly. For example:
If, instead of accessing the attributes of a class directly, you write accessor functions, you
can make all your accesses through a single section of code. When you initially write your
accessor functions, they might look as follows:
<?php
class Car
{
private $make;

function __get($name)
{
return $this->$name;
}

function __set($name, $value)


{
$this->$name = $value;
}
}

$car = new Car;


$car->make = 'Toyota';
echo $car->make; // Toyota

Note!The __get() function simply returns the value of the property, while
the __set() function assigns a value to a property. __get() takes a single parameter,
and __set() uses two. These functions do not get called directly! They have special
meaning in PHP just like __construct() and __destruct(). When trying to set or get
properties by something like $car->make = 'Toyota'; or echo $car->make;, what happens
is under the hood, the __set() or __get() functions get magically called for you with the
parameters supplied! So what’s the benefit you ask? Well, you could write
the __set() function so that it filters or restricts what data can be assigned. Maybe we
don’t like Chevy cars. Well we can prevent our objects from becoming Chevys like so:
<?php

class Car
{
private $make;

function __get($name)
{
return $this->$name;
}

function __set($name, $value)


{
if( $value !== 'Chevy'){
$this->$name = $value;
}
}
}

$car = new Car;


$car->make = 'Chevy';
var_dump($car->make); // null
Now, try as you may to assign Chevy to the make property, it will retain a null value.
Declaring Constants
You can assign constants within a class by using the const keyword. Access is similar to
that of static properties in that you use the self keyword or :: operator like so:
<?php

class Car
{
const WHEELS = 4;
const ENGINE = 1;
}
echo Car::WHEELS; // 4

Inheritance
When we want to inherit methods or properties from a class we must use
the extendskeyword. We could extend our Car class like so:
<?php

class Racecar extends Car { }

$racecar = new Racecar;


$racecar->make = 'Nissan GTR';
echo $racecar->make; // Nissan GTR

Cool! You’ll
note that that there are no property or method definitions whatsoever in
our Racecar class, yet we can still set and get the make of our new Racecar! That is
because Racecar has inherited everything from Car by way of the extends keyword.
Private and Protected
If you are not specifying otherwise, everything from the base class will get extended to the
child. You may want to limit what can be inherited though. In that case you could use
either private or public like so:
<?php

class Car
{
private $make = 'Nissan';
protected $topspeed = 125;
public $color = 'Green';
}

class Racecar extends Car


{
function getMake(){
return $this->make;
}
function getTopSpeed(){
return $this->topspeed;
}
}

$racecar = new Racecar;


// method access to properties inside the extended class
echo $racecar->getMake(); // fail (private)
echo $racecar->getTopSpeed(); // works (protected)

// trying to access properties outside the class


echo $racecar->make; // fail (private)
echo $racecar->topspeed; // fail (protected)
echo $racecar->color; // works anywhere in or outside the class (public)

We can also control the access to methods like so:


<?php

class Car
{
public $make = 'Nissan';
public $topspeed = 125;
public $color = 'Green';

public function getMake(){


return $this->make;
}

private function getTopSpeed(){


return $this->topspeed;
}

protected function getColor(){


return $this->color;
}
}

class Racecar extends Car {


function make(){
return $this->getMake();
}

function speed(){
return $this->getTopSpeed();
}

function color(){
return $this->getColor();
}
}

$racecar = new Racecar;


// method calls on the child outside the class
echo $racecar->getMake(); // works (public)
echo $racecar->getTopSpeed(); // fail (private)
echo $racecar->getColor(); // fail (protected)

// method calls inside the child class


echo $racecar->make(); // works (public)
echo $racecar->speed(); // fails (private)
echo $racecar->color(); // works (protected)

Interfaces
Interfaces are becoming more popular in use. The Laravel Framework and it’s community
is especially keen on their use. Interfaces are a contract that define what methods a class
must implement. Any class that implements the interface must provide implementations for
all methods in the interface. The benefits to using an interface are many, once an
application begins to grow in size. Testing, code maintenance, and swapping of
implementations are the main factors to consider. An example interface might look
something like this:
<?php

interface Raceable
{
function hitTheGas();
}

class Racecar implements Raceable


{
function hitTheGas()
{
echo "Putting the pedal to the metal";
}
}

Note that the interface is merely a definition, it does not contain any actual code!
Constructors
No discussion of object oriented programming is complete without talking about
constructors. Constructors are very useful to us for setting default values and getting our
object ready for use right away. They also allow us to pass arguments to our objects as
they are created. Let’s rewrite our Car class using a constructor:
<?php

class Car
{
public $make;
public $topspeed;
public $color;

public function __construct($make, $topspeed, $color){


$this->make = $make;
$this->topspeed = $topspeed;
$this->color = $color;
}
}

$car = new Car('Honda', 110, 'Red');

var_dump($car);

object(Car)[1]
public 'make' => string 'Honda' (length=5)
public 'topspeed' => int 110
public 'color' => string 'Red' (length=3)

This is great! We can see that as soon as the object is created, it’s key properties are set
right away. Let’s make one more $car object and pass in different parameters just to be
sure it works:
<?php

$car = new Car('Kia', 120, 'Gray');

var_dump($car);

object(Car)[1]
public 'make' => string 'Kia' (length=3)
public 'topspeed' => int 120
public 'color' => string 'Gray' (length=4)

Yes this is working just as we expect!


Destructors
Though not as useful or important as constructors, destructors are worth a mention.
Basically, a destructor is the opposite of a constructor. When the last reference to an
object is removed or the end of the script is reached, the destructor gets called. The
intention is to unset and clean up resources at this point. In reality, since PHP
automatically cleans up all resources as soon as they fall out of scope, we don’t really
need to worry about it. If you needed to, this is how to write a destructor:
<?php

class Car
{
public $make;
public $topspeed;
public $color;

public function __construct($make, $topspeed, $color){


$this->make = $make;
$this->topspeed = $topspeed;
$this->color = $color;
}

function __destruct(){
echo 'Turning the Car off now.';
}
}

Conclusion
Object Oriented PHP is a large topic and one blog post can not do it justice! This was
however, a great overview of the key terms, techniques, and ideas when beginning to
learn OOP in PHP. Since we like to talk about and implement many of the great PHP
frameworks, it is mandatory that we know how their object oriented core works under the
hood. I hope you found some good bits of information here whether you are a beginner or
even a more experienced programmer just brushing up on the fundamentals.

Composer Dependency Tutorial

You’ve likely heard of Composer, the dependency management system for


PHP. If you’ve been following along with our Laravel Tutorials, you’ll note that
we have been making use of Composer to get our projects up and running.
Whether you have Composer running on a *nix system like Ubuntu, or
Composer running on a Mac or Windows, the process is essentially the same.
Let’s dig into Composer a bit more so that we have a solid grasp of what it is,
how it works, and how to best use it.

The Director of the Symphony


When you visit the home page for Composer, they have a nice picture of an actual
Composer who would be directing a Symphony. Think of all those nice folks playing their
various instruments as various pieces of software with the Composer being the director
that helps them all work together. Just as a real Composer helps musicians and
instruments work together to create something bigger than any one of them could do
alone, the software Composer acts as a director of sorts that manages dependencies and
relationships between various PHP software packages. Cool stuff indeed!

Framework Agnostic
We’ve been using composer with our Laravel projects and tutorials, but Composer is much
bigger than that. By using Composer you can plug in software packages into your favorite
PHP framework, whether that be Laravel, Codeigniter, Yii, Symfony, Zend, Slim, FuelPHP,
and more. The benefit here is that you do not become so much dependent on learning all
of the different nuances of a framework, only to have to start over if you need to work on a
different project that uses a different framework.

Install Composer
First up, we need to install Composer. We can do this easily on *nix or Windows systems.

*nix based
$ cd /var/www/mykillerapp
$ curl -s http://getcomposer.org/installer | php
To see all the commands available to run you can do the following
$ php composer.phar

Windows Based
For the lazy among us the like a one click installation,
click https://getcomposer.org/Composer-Setup.exe and run the program. The installer
downloads composer and configures the system so you can run composer from any
directory. In fact, in windows explorer, if you right click on various folders you’ll see options
like Composer Init, Composer Options, Self Update, Show Help, Run as Admin, and Use
Composer Here. Quite handy indeed!

Available Commands
Once Composer is installed you can run a slew of commands from the command line. Hit
the official docs for the exhaustive details, or check out this list here of the most commonly
used ones you might run into: install, update, require vendor-name/package-
name, init, create-project symfony/framework-standard-edition dir/, run-
script, search my keywords, validate, config --list, self-
update, status, diagnose, help, show, global, licenses, archive, depends vendor-
name/package-name, dump-autoload --optimize
Check out this awesome Composer Cheat Sheet for Developers for an explanation of each
command.

composer.json
The configuration file for Composer is your composer.json file. It contains everything to tell
Composer how to operate and consists of, you guessed it, json data! The data within
specifies settings and package requirements for a given application. A really
basic composer.json file would look like this:
{
"require": {
"lego/pieceofresistance": "*"
}
}

This will require the “pieceofresistance” package, created by “lego”, and will require any
version. More commonly, you might like to use a specific verison like this:
"lego/pieceofresistance": "2.0.3"
Often times you will see major versions specified and minor versions given the wildcard
like this:
"lego/pieceofresistance": "2.0.*"
Cool! You now have a package (fictional in this case) so you can run the installcommand.
This is when the magic starts happening. If you remember manually trying to find and
download different scripts to try out on your local server, rejoice! With this approach, the
files start downloading in the background and get placed into the vendors/ folder at the
root of the application. Better yet is to specify where you would like the files placed in
the composer.json like so:
{
"require": {
"lego/pieceofresistance": "2.0.*"
},
"config" : {
"vendor-dir" : "packages"
}
}
Let’s now actually use Composer to specify some packages to download. The first
example will be an really fantastic PHP Console that you can use for testing snippets of
PHP without having to actually create a PHP file, save it, load it, and so on. We’ll make
use of the seld/php-console package.

Using composer init


Composer init helps guide you through the process of creating a valid json file for
Composer to use.

C:wampwwwphpcon>composer init
Welcome to the Composer config generator
This command will guide you through creating your composer.json config.
Package name (/) [vegibit/phpcon]: demo/forfun
Description []: just a test of composer
Author: fred
Minimum Stability []: dev
License []:
Define your dependencies.
Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no
{
“name”: “demo/forfun”,
“description”: “just a test of composer”,
“authors”: [
{
“name”: “fred”,
“email”: “fred@flinstone.com”
}
],
“minimum-stability”: “dev”,
“require”: {
}
}
Do you confirm generation [yes]? y
C:wampwwwphpcon>
If we now look at the composer.json file created for us, it will appear as so:
{
"name": "demo/forfun",
"description": "just a test of composer",
"authors": [
{
"name": "fred",
"email": "fred@flinstone.com"
}
],
"minimum-stability": "dev",
"require": {

}
}

We didn’t specify any dependencies during the composer init command, so you’ll see that
the require object is empty. We can manually update it once we find something
from https://packagist.org/ that we would like to use. In this example we are going to
use https://packagist.org/packages/seld/php-console. We can now
update composer.json manually like so:
{
"name": "demo/forfun",
"description": "just a test of composer",
"authors": [
{
"name": "fred",
"email": "fred@flinstone.com"
}
],
"minimum-stability": "dev",
"require": {
"seld/php-console": "1.4.*"
}
}

Now pretend you didn’t do this manually, or simple delete any entries in the require object.
We can also complete the same task using composer require
C:wampwwwphpcon>composer require
Search for a package []: seld
Found 3 packages matching seld
[0] seld/jsonlint
[1] seld/php-console
[2] seld/slippy
Enter package # to add, or the complete package name if it is not listed []: 1
Enter the version constraint to require []: 1.4.0
Search for a package []:
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
– Installing seld/php-console (1.4.0)
Loading from cache
Writing lock file
Generating autoload files
C:wampwwwphpcon>
Excellent! This updates your composer.json file and pulls in the dependencies in one shot.

Note that there is also a new file in the directory called composer.lock. This is a *very*
important file! Basically what it does is lock in the versions you have specified in
the composer.json file so that if you or someone else runs composer install in the future,
only those specified versions will be installed, *not* the latest and greatest versions which
might cause bugs or breakage of your app.
You can bypass this by using composer update. What this command does is pretend that
a composer.lock file is not there, or just ignores it. Composer will look for any
wildcard * characters in the composer.json file and download the latest versions for the
dependencies. Maybe you want this, maybe you don’t. Just be aware of the difference
between composer install and composer update.
If you look in the project directory you’ll now notice a vendor directory in addition to
the composer.json and composer.lock files. If we open up the vendor directory, you’ll see
the composer folder and the seld folder dependency in addition to an autoload.php file.
Inside of the seld folder we have the package we were looking for, php-console. Now
check this out, let’s browse to http://localhost/phpcon/vendor/seld/php-console/ and
observe the result in all of it’s glory:

There you go. Your own PHP console sandbox to quickly test snippets of code with the
click of a button. No downloading all kinds of zip files, extracting them, copy and paste,
none of it. Just use composer, enter a few commands, and get yourself a nice piece of
software to test and use.
Lets add another requirement to this project.
C:wampwwwphpcon>composer require
Search for a package []: twitter/bootstrap
Found 15 packages matching twitter/bootstrap
[0] twitter/bootstrap
[1] libra/twitter-bootstrap-assets
[2] mwillbanks/zfc-twitter-bootstrap
[3] kvdh/symfony-twitter-bootstrap
[4] toa/twitter-bootstrap-bundle
[5] phpugl/twitter-bootstrap-bundle
[6] evheniy/twitter-bootstrap-bundle
[7] typo3/twitter-bootstrap
[8] jlong/sass-twitter-bootstrap
[9] kvdh/symfony-twitter-bootstrap-datetime-picker
[10] twitter/bootstrap-bundle
[11] ppi/twitter-bootstrap-module
[12] patricktalmadge/bootstrapper
[13] komola/bootstrap-zend-framework
[14] yiisoft/yii2-bootstrap
Enter package # to add, or the complete package name if it is not listed []: 0
Enter the version constraint to require []: dev-master
Search for a package []:
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
– Installing twitter/bootstrap (dev-master 541a75f)
Downloading: 100%
Writing lock file
Generating autoload files
C:wampwwwphpcon>
Again, this updates our composer.json and pulls in the dependency all at once, cool!
Using Composer is a great way to simplify workflow and manage dependencies in your
PHP projects, whether you’re working on UNIX, Linux, Mac, or Windows. Not only that,
Composer offers powerful autoloading features that we’ll tackle in our next episode. Try it
out today and see what you think.

Composer Autoloading Tutorial


We’ve been taking a closer look at using Composer to manage dependencies
in our PHP projects. Getting up to speed with composer takes some practice
and diligence just like any other part of programming. There is a bit of a
learning curve, and while you can do all the things Composer offers manually, if
you take the time to learn the tool, your workflow will be more streamlined and
efficient. It’s a lot like Laravel actually. Laravel teaches you to use better coding
practices, and if you are new to them, your programming speed will probably
actually decline at first. Much like using Composer however, if you put in the
time up front to learn more efficient ways of doing things, it will benefit you
greatly in the longer run. In this episode we’ll take a closer look
at Autoloading using Composer.

Four Ways to Autoload


With composer, you specify in your composer.json file how and what you will autoload for a
given project. There is an autoload object within the composer.json which you can populate
with one or more of these four techniques to make use of autoloading. You have the option
of File Based Autoloading, Classmap Based Autoloading, PSR-0 Autoloading,
and PSR-4 Autoloading. These would be referenced by the keys filesclassmap psr-
0 and psr-4. At the time of this writing, the official documentation for Composer is
recommending PSR-4, but we’ll take a look at all four options.

1. File Based Autoloading


First up we’ll do a simple example of File Based Autoloading using Composer.

1. In our web root, create a folder named aldemo, for auto load demo.
2. Now we can add a folder to hold our custom code. We can call it mylibrary
3. Add a functions.php file in there, and define a custom function for yourself. We’ll use
this one, but you can create your own if you like.

4. Now we can use Composer to generate the autoload files for us. Create
a composer.json file and place it in the aldemo folder like so:

5. Run composer dump in the aldemo folder. It will note that it is Generating autoload
files for you.
6. Create an index.php file in the aldemo folder and make a call to your new function.
We simply did this:

7. Now load up your page in the browser http://localhost/aldemo/ and see the result.
Ouch. That didn’t work out so well: Fatal error: Call to undefined function lego() in
C:wampwwwaldemoindex.php on line 3
8. We still need to include the autoloader like so! require 'vendor/autoload.php';.
Your index.php will now look like:
9. Once again go ahead and visit http://localhost/aldemo/ and observe that yes, You
are now a master builder.

2. Classmap Based Autoloading


Now we can take a look at how to do Classmap Based Autoloading. This one is better
than files since you don’t have to specify the actual file itself, just the directory it lives in.
We used this approach in our Custom Helper Functions in Laravel Episode.

1. Create a folder called classmap in the aldemo folder.


2. Add a functions.php file that contains some simple logic, we’ll use this:

Note that you need to use a Class! The classmap loads only Classes, whereas
with files, you can load native functions.

3. Update your index.php to include a call to the new function:


4. Update your composer.json like so:

The naming might not have been the best for this example, but it will do. You’ll see
the new classmap object within the autoload object, and it now has an array with one
value, classmap. That says, “We are using a classmap, and I want you to look in the
classmap folder to autoload any classes you find.”

5. Run composer dump in the aldemo folder


6. Load http://localhost/aldemo/ and you’ll see that You are now a master builder,
that knows how to autoload with a classmap!

3. PSR-0 Based Autoloading


At this point we’ll get just slightly more advanced and make use of PSR-0 autoloading. I’m
not one for crazy verbiage so if you want every single detail, read the spec. For me, PSR-
0 just means we’re using namespaces in this convention <Vendor
Name>(<Namespace>)*<Class Name>. The main point is the namespaces need to follow the
folder structure.
1. Ok we know that aldemo is our root folder, so lets add the following folders into this
directory /src/vegibit/library.
2. Now, we can create a greeting.php class file in the /src/vegibit/library folder. It
will hold two namesspaces like so:

Now hold on just a minute! You have two different namespaces in the
same greeting.php class file. Not only that, each namespace has the exact same
class name and method name! Normally PHP would unleash a rath of fury and anger
upon you if you tried to do this without namespaces! This is the benefit of
namespaces however, you can have classes and methods that use the same name,
as long as they are in their own namespace. Excellent!

3. Let’s update our composer.json so that it has the needed info to load these classes
using PSR-0
Now check it out. What this configuration says is,
“The VegibitLibrary and VegithemesLibrary namespaces both live in
the src directory.

4. Run composer dump to update our autoload files.


5. Now that all of our plumbing is in place, we can use our new code in
the index.php file. Let’s update it like so:
6. Finally, we can visit http://localhost/aldemo/ and find that You are now a master
builder, that knows how to autoload with a classmap! We got you covered with
Free Twitter Bootstrap Themes! Awesome!

4. PSR-4 Based Autoloading


PSR-0 has been the cutting edge method of using autoloading in PHP… until now. The
new kid on the block is PSR-4 autoloading. At the time of this writing, PSR-4 is the
recommended method of autoloading according to the official Composer Documentation.
So what’s the big deal with this PSR-4 business? Let’s examine.
With PSR-0, we needed to map our namespaces exactly to our directory structure. This
turns out to create a lot of empty folders in the file system, which might not be the best way
to do things. In some respects, I think it actually helps to keep the consistency. On the
other hand, why create such a verbose directory structure if you don’t have to? Well,
in PSR-0, you have to. In PSR-4 however, you can shorten your directory structure while
still using the same lengthy namespacing.

1. Let’s remove our greeting.php class file from aldemo/src/vegibit/library and


place it in the aldemo/src directory.
2. Delete the vegibit/library directories. We are now left
with aldemo/src/greeting.php.
3. Now, at this point, we have the same greeting.php class file, and it uses the same
namespacing within the file, and our code in the index.php file is trying to use these
classes in the same way. The only difference is that we moved the physical location
of the file from aldemo/src/vegibit/library to aldemo/src. In our composer.json, we
already said that our Vegibit/Library and Vegithemes/Library namespaces live in
the src directory, so in theory this should all still work right? Let’s try:
4. Load up http://localhost/aldemo/ and whoops, Fatal error: Class
‘VegibitLibraryGreeting’ not found in C:wampwwwaldemoindex.php on line 10.
Ok, it’s not working. Well, what we just did was basically break the rules of PSR-0,
which is that the directory structure must follow the namespaces.
5. Let’s make just a small tweak to our composer.json file. It now looks like this:

We changed psr-0 to psr-4, and added \ to the end of our namespaces which is a
requirement of psr-4.

6. Run composer dump


7. Visit http://localhost/aldemo/ one more time and find that, yes, You are now a
master builder, that knows how to autoload with a classmap! We got you
covered with Free Twitter Bootstrap Themes! It works!

So you see, using PSR-0, developers were forced to use lengthy directory structures
which created a lot of empty directories. This was only needed to make the autoloader
work. With PSR-4, we no longer have to use such verbose directory paths.

Composer Autoloading Conclusion


We covered a lot of ground here! We had a good look at the four methods of using
autoloading in Composer. We can use files, classmaps, psr-0, and psr-4. It is most
definitely worth the time to learn Composer and make use of all the benefits it can provide
you with!
PHP Namespaces Tutorial

If you come from the C sharp or Java World, namespaces are not a new idea to
you. In PHP, it was only once PHP 5.3 was released that namespaces gained
official support in the language. Namespaces are changing the way applications
in PHP are written, and they are likely one of the most important additions to
the language in recent times. In this episode, we’ll take a look at what
namespaces are, why they benefit us, and how to use them. Let’s dig in!

What Problems Do Namespaces Solve?


As you began your PHP programming, you likely found that over time as your programs
became larger, things started to become cluttered and hard to find. In addition to this, you
may have started to add libraries from other developers. Adding more classes and method
names to your project starts to become problematic without namespaces because if you
have a class or method with the same name, your program will fail. This is called having
collisons. With namespaces, we fix the problem of collisions in our codebase.
Namespaces support PHP classes, functions, and constants.

PHP Namespace Example


Before namespaces, all PHP code just lived in a global namespace. We can place a piece
of PHP code into a namespace by using the namespace command like so:
<?php
namespace Vegibit;

Any PHP code that comes after this line now lives in the Vegibit namespace. You can also
define more than one namespace in the same PHP file like so:
<?php
namespace Google;

Class Search {

public function query() {


return 'Searching Google';
}
}
namespace Bing;

Class Search {

public function query() {


return 'Searching Bing';
}
}
?>

Truth be told, it’s probably a good idea to keep your namespace to one per PHP file. After
all, you’re using namespaces to reduce collisions and confusion in the application, no need
to complicate things. The above example does highlight nicely the benefit of namespaces
however. Notice that both the Google and Bing namespace each have a class named
search and a method named query? You can’t do that in the global namespace! Since we
declared these classes and methods in different namespaces however, we can use each
class and method to our hearts content, with no need to worry about running into
collisions.

PHP Namespace Hierarchy


Most times you will see namespaces following the convention of matching a folder
structure. By using a backslash character between folder names so to speak, you can
define very precise naming conventions for where your libraries and PHP code lives.
Maybe you have some code that deals with the Facebook API. You might declare code in
that folder like so, namespace VegibitFacebook while your database code might
be namespace VegibitDatabaseMySQL and common helper methods might use namespace
VegibitCommonStringHelpers. It is very flexible.

How To Use Namespaced Code


So far we have only looked at how to define namespaces and place code within them.
What about when we need to actually make use of that code? Let’s take a look at a
namespace example to demonstrate. We’ll create a file named vegilib.php and define a
constant, function, and class with the Applicationvegilib namespace. Check it out:
vegilib.php
<?php
// application library
namespace Applicationvegilib;

const MAXVALUE = 'Infinity';

function learning() {
return 'Get your learn on';
}

class Organization {
static function teamplayer() {
return 'There is no I in team';
}
}

To call this code, we can use PHP just like this:


application.php
<?php
require('vegilib.php');

echo ApplicationvegilibMAXVALUE . '<br>';


echo Applicationvegiliblearning() . '<br>';
echo ApplicationvegilibOrganization::teamplayer() . '<br>';

Results in:

Infinity
Get your learn on
There is no I in team

You’ll note that we had to use the full namespace path in order for this code to run
successfully. This is what is referred to as a fully qualified namespace and includes the
initial backslash. So what happens if we just put this application code inside the same
namespace? Let’s see!
application.php (namespaced)
<?php
namespace Applicationvegilib;

require ('vegilib.php');

echo MAXVALUE . '<br>';


echo learning() . '<br>';
echo Organization::teamplayer() . '<br>';

Infinity
Get your learn on
There is no I in team

Awesome! Since we now have the application code living in the same namespace, you can
see that instead of having to use the full path in our execution code, we can simply access
our constant, function, and class method directly since we are in the same namespace.

Importing Namespaces
As we just saw, you can place your application code into the same namespace as your
library, and this will give you direct access to the guts of that library without having to
specify the fully qualified namespace. Let’s look at importing namespaces using
the use and as keywords, it’s quite slick! We’ll break up our earlier example of the Google
and Bing namespaces into separate class files for this example.
google.php
<?php
namespace Google;

Class Search {

public function query() {


return 'Searching Google';
}
}

bing.php
<?php
namespace Bing;

Class Search {

public function query() {


return 'Searching Bing';
}
}

If we update our application.php file to the following:


<?php
use Google as g;
use Bing as b;

require ('google.php');
require ('bing.php');

$searchengine = new gSearch;


echo $searchengine->query() . '<br>';

$searchengine = new bSearch;


echo $searchengine->query() . '<br>';

Results in
Searching Google
Searching Bing

We’ll now find that we can search Google and Bing using the same Class and Method
names, just from another namespace. Make note of both use Google as g; and use Bing
as b;. What this says is that we want to use each namespace as something else. So in the
case of the Google namespace, we can instantiate an object like this $searchengine = new
gSearch; and to instantiate an object in the Bing namespace we can do this $searchengine
= new bSearch;
If we omit the lines:
<?php

use Google as g;
use Bing as b;

we can still use those classes and methods but we’ll now have to include the full
namespace when trying to instantiate an object like this:
<?php

require ('google.php');
require ('bing.php');

$searchengine = new GoogleSearch;


echo $searchengine->query() . '<br>';

$searchengine = new BingSearch;


echo $searchengine->query() . '<br>';

Searching Google
Searching Bing

Some of this is a matter of preference, while some of this is quite nuanced to the point of if
you don’t follow the conventions very specifically, your app will break. When in doubt, hit
up the official docs and various definitions and rules to be sure you are following the best
practices.

What is __NAMESPACE__ ?
This is a constant that refers to the current namespace. In the global namespace, this
constant has no value, or an empty string. Let’s adjust our most recent application code to
test this out:
<?php
namespace Bing;
use Google as g;

require ('google.php');
require ('bing.php');

$searchengine = new gSearch;


echo $searchengine->query() . '<br>';

echo __NAMESPACE__;
Now what we have here is a snippet of PHP code that lives in the Bing namespace. Within
this namespace we import the Google namespace and alias it as the letter g. Therefore,
the object creation and method call runs, and we search google. Be echoing out the
__NAMESPACE__ constant, we can see that yes, this file does live in the Bing
namespace.
Searching Google
Bing

So what is this good for? A good question indeed! It turns out you can use this constant for
debugging purposes as well as to create dynamically generated fully qualified class
names.

Namespaces and Autoloading


Namespaces are going to be key for you to use autoloading in your PHP projects moving
forward. Like we mentioned in this Composer Autoload Tutorial, Composer makes heavy
use of Namespaces in order for it to work it’s magic. By learning your Namespaces as well
as your psr-0 and psr-4 standards, you will be well equipped to deal with the new methods
of PHP workflow.

The Ultimate PHP String Functions List

Welcome to the Ultimate PHP String Functions List with 70 Must Know PHP
String Functions. You can find all kinds php string functions tutorial articles
online, however this php string functions cheat sheet will be the ultimate guide
to using string functions in php. We took an exhaustive approach in coming up
with the list and sorted the entire list based on frequency of use in the PHP
community, usefulness, and importance of learning with regard to your php
development. You can use this list to study for php string functions interview
questions, or just to brush up on your own skills for self improvement. However
you use the list is up to you. Now Let’s dig in to the ultimate list of php string
functions.

When you’re starting with PHP, it’s so easy to be overwhelmed by the sheer number of
functions available to you. In this episode we happen to be studying php strings. Now what
makes this list useful, maybe even more useful than just the list the documentation
provides, is that we ran a program over the top php repositories online today and found out
how many times each of these functions was used overall. This tells us what functions the
pros are using, so it makes sense to focus on the ones that are giving the most mileage to
them. That means the php string functions we have here, especially the ones near the top
of the list, are extremely useful and will be the ones that we first learn and commit to
memory.

• 1substr()
• 2strlen()
• 3sprintf()
• 4echo()
• 5strpos()
• 6implode()
• 7str_replace()
• 8strtolower()
• 9explode()
• 10chr()
• 11trim()
• 12str_repeat()
• 13strtoupper()
• 14str_pad()
• 15ord()
• 16strtok()
• 17strstr()
• 18rtrim()
• 19md5()
• 20strrpos()
• 21join()
• 22bin2hex()
• 23ltrim()
• 24substr_replace()
• 25str_split()
• 26sha1()
• 27ucfirst()
• 28chunk_split()
• 29ucwords()
• 30htmlspecialchars()
• 31stripos()
• 32substr_count()
• 33number_format()
• 34stripcslashes()
• 35strstr()
• 36wordwrap()
• 37addcslashes()
• 38parse_str()
• 39strcmp()
• 40strip_tags()
• 41substr_compare()
• 42setlocale()
• 43str_ireplace()
• 44strncasecmp()
• 45crypt()
• 46printf()
• 47quoted_printable_decode()
• 48sscanf()
• 49crc32()
• 50htmlentities()
• 51levenshtein()
• 52strcasecmp()
• 53strcspn()
• 54strripos()
• 55strspn()
• 56html_entity_decode()
• 57str_shuffle()
• 58stristr()
• 59strpbrk()
• 60strrev()
• 61addslashes()
• 62count_chars()
• 63md5_file()
• 64nl2br()
• 65sha1_file()
• 66str_word_count()
• 67strnatcasecmp()
• 68strnatcmp()
• 69strncmp()
• 70chop()
1. substr() definition: The substr() function returns a part of a string.
Usage:If you know where the information that you want lies in a larger string, you can
extract it out with the substr() function.

substr function signature substr(string, start, length)


Argument Argument Meaning

string Mandatory. Specifies the string to return a part of

start Mandatory. Specifies where to start in the string

• A positive number – Start at a specified position in the string


• A negative number – Start at a specified position from the end of the string
• 0 – Start at the first character in string

length Not Mandatory. Specifies the length of the returned string. Default is to the end of the string.

• A positive number – The length to be returned from the start parameter


• Negative number – The length to be returned from the end of the string

Code Example
<?php
$sentence = "The Apple iPhone 6 Plus is cool, just don't bend it";
$one = substr($sentence, 9, 10);
$two = substr($sentence, 24, 27);

echo $one.' - ';


echo $two;
?>

iPhone 6 – is cool, just don’t bend it

2. strlen() definition: The strlen() function returns to us the number of characters in the
string it’s given.
There are many times when you will need to know the length of a string.
Usage:
The strlen() function makes this super easy for us.
strlen function signature strlen(string)
Argument Argument Meaning

string Mandatory. This is the string that we will check the length of.

Code Example
<?php

$length = strlen("What is the length of Ariana Grande, Kate Upton, Nicki Minaj, and Selena Gomez?");

echo $length;

?>

79

3. sprintf() definition: The sprintf() function returns a string created by fillingformat with
the given arguments.
Usage: The sprintf() function can be used to assign a formatted string to a variable.
The arg1, arg2, ++ parameters are inserted at the percent (%) signs in the main
string. sprintf() works in a step by step fashion meaning at the first % sign, arg1 is
inserted, at the second % sign, arg2 is inserted, and so on.

sprintf function signature sprintf(format, arg1, arg2, arg++)


Argument Argument Meaning

format Mandatory. Specifies the string and how to format the variables in it.

Possible format values:

• %% – Returns a percent sign


• %b – Binary number
• %c – The character according to the ASCII value
• %d – Signed decimal number (negative, zero or positive)
• %e – Scientific notation using a lowercase (e.g. 1.2e+2)
• %E – Scientific notation using a uppercase (e.g. 1.2E+2)
• %u – Unsigned decimal number (equal to or greather than zero)
• %f – Floating-point number (local settings aware)
• %F – Floating-point number (not local settings aware)
• %g – shorter of %e and %f
• %G – shorter of %E and %f
• %o – Octal number
• %s – String
• %x – Hexadecimal number (lowercase letters)
• %X – Hexadecimal number (uppercase letters)

Additional format values. These are placed between the % and the letter (example %.2f):

• + (Forces both + and – in front of numbers. By default, only negative numbers are marked)
• ‘ (Specifies what to use as padding. Default is space. Must be used together with the width specifier.
Example: %’x20s (this uses “x” as padding)
• – (Left-justifies the variable value)
• [0-9] (Specifies the minimum width held of to the variable value)
• .[0-9] (Specifies the number of decimal digits or maximum string length)

Note: If multiple additional format values are used, they must be in the same order as above.

arg1 Mandatory. The argument to be inserted at the first %-sign in the format string

arg2 Not Mandatory. The argument to be inserted at the second %-sign in the format string

arg++ Not Mandatory. The argument to be inserted at the third, fourth, etc. %-sign in the format string

Code Example
<?php

$first_name = 'President';
$last_name = 'Business';

$hello = sprintf("Hello there, %s %s", $first_name, $last_name);


echo $hello;

?>

Hello there, President Business

4. echo() definition: The echo() function outputs strings and information to the browser.
Usage: You’ll make use of echo() constantly. Technically, echo() is not actually a function
but a language construct. As such, in almost all use cases you will omit the parenthesis
entirely.

echo function signature echo(strings)


Argument Argument Meaning
strings Mandatory. One or more strings to be sent to the output

Code Example
<?php

$verb = 'am chilling';


$state = 'cool';
$person = 'Mr. Brickowski';

echo "I $verb with a Snapple Iced Tea.<br>";


echo "Isn't that pretty $state?<br>";
echo "<span class='label label-info'>Why yes, Yes it is $person.</span></div>";

?>

I am chilling with a Snapple Iced Tea.


Isn’t that pretty cool?
Why yes, Yes it is Mr. Brickowski.
This small snippet shows how we can echo out strings to the screen. We used double
quotes to make use of interpolation for these examples.

5. strpos() definition: The strpos() function returns the position of the first occurrence
of find in string. If specified, the function begins its search at positionstart. Returns false if find is
not found.
Usage: You can use the strpos() function to find the first occurrence of a small string in a
larger string and if the small string isn’t found, strpos() returns false.

strpos function signature strpos(string, find, start)


Argument Argument Meaning

string Mandatory. Specifies the string to search

find Mandatory. Specifies the string to find

start Not Mandatory. Specifies where to begin the search

Code Example
<?php
$string = '0123456789';
$find = '7';
$start = 0;

$result = strpos($string, $find, $start);

echo $result;

?>

7
The code above uses a string of characters that represent numbers as a string. These are
not real numbers, they are of type string not int or float! We simply use this to illustrate that
when using this function the very first character in a string starts with zero. For every single
character including any whitespace, the number increments by one. We start at the first
position of 0 in the example, but had we started at 8 for example, then the function would
have returned false since it was looking for 7, but started looking at the eighth position so it
already missed it.

6. implode() definition: The implode() function does the exact opposite ofexplode() – it
creates a large string from an array of smaller strings.
Usage: Returns a string created by joining every element in the array with separator.

implode function signature implode(separator, array)


Argument Argument Meaning

separator Not Mandatory. Specifies what to put between the array elements. Default is “” (an empty string)

array Required. The array to join to a string

Code Example
<?php

$fields = array('iPhone', 'Macbook', 'Lenovo Ultrabook', 'Vacation at Cape Cod');


$string = implode(' @@ ', $fields);

echo $string;

?>

iPhone @@ Macbook @@ Lenovo Ultrabook @@ Vacation at Cape Cod


7. str_replace() definition: The str_replace() function replaces some characters with
some other characters in a string.
Usage: Searches for all occurrences of find in string and replaces them with replace. If all
three parameters are strings, a string is returned. If string is an array, the replacement is
performed for every element in the array and an array of results is returned.
If find and replace are both arrays, elements in find are replaced with the elements
in replace with the same numeric indices. Finally, if find is an array and replace is a
string, any occurrence of any element in find is changed to replace. If supplied, count is
filled with the number of instances replaced.

str_replace function signature str_replace(find, replace, string, count)


Argument Argument Meaning

find Mandatory. Specifies the value to find

replace Mandatory. Specifies the value to replace the value in find

string Mandatory. Specifies the string to be searched

count Not Mandatory. A variable that counts the number of replacements

Code Example
<?php
$strings = array (
'You like to have a great experience',
'You are a really nice individual',
'Do you like to drink Dunkin Donuts?'
);

$search = array (
'great',
'experience',
'individual',
'Dunkin Donuts'
);
$replace = array (
'fantastic',
'time',
'person',
'Starbucks'
);
$replaced = str_replace ( $search, $replace, $strings );

print_r ( $replaced );
?>

Array
(
[0] => You like to have a fantastic time
[1] => You are a really nice person
[2] => Do you like to drink Starbucks?
)

8. strtolower() definition: The strtolower() function turns a mixed case string into all
lowercase characters.
Usage:Returns string with all alphabetic characters converted to lowercase. The table used
for converting characters is locale-specific.

strtolower function signature strtolower(string)


Argument Argument Meaning

string Mandatory. Specifies the string that we will convert to all lowercase.

Code Example
<?php
function chill($string) {

return strtolower ( $string );


}

$person = 'BUDDY CAN YOU TURN OFF THE CAPS LOCK KEY?!';

echo chill ( $person );


?>

buddy can you turn off the caps lock key?!

9. explode() definition: The explode() function breaks apart a string into an array.
Usage:If you know where the information that you want lies in a larger string, you can
extract it out with the explode() function.

explode function signature explode(separator, string, limit)


Argument Argument Meaning

separator Mandatory. Specifies where to break the string

string Mandatory. The string to split

limit Not Mandatory. Specifies the number of array elements to return.

Possible values:

• Greater than 0 – Returns an array with a maximum of limit element(s)


• Less than 0 – Returns an array except for the last -limit elements()
• 0 – Returns an array with one element

Code Example
<?php
$string = "Your mind is so prodigiously empty that there is simply nothing left to empty out.";
print_r (explode(' ',$string));
?>

Array
(
[0] => Your
[1] => mind
[2] => is
[3] => so
[4] => prodigiously
[5] => empty
[6] => that
[7] => there
[8] => is
[9] => simply
[10] => nothing
[11] => left
[12] => to
[13] => empty
[14] => out.
)
10. chr() definition: The chr() function returns a character when you pass it an ASCII value.
Usage: Returns a string consisting of the single ASCII character ascii.

chr function signature chr(ascii)


Argument Argument Meaning

ascii Mandatory. An ASCII value

Code Example
<?php
// Decimal value
echo chr(33);
echo chr(34);
echo chr(35);

// Octal values
echo chr(110);
echo chr(111);
echo chr(112);

// Hex values
echo chr(0x52)
?>

!”#nopR

11. trim() definition: The trim() function cleans a string of all whitespace or other specified
characters.
Usage:Returns string with every whitespace character in charlist stripped from the
beginning and end of the string. You can specify a range of characters to strip
using .. within the string. For example, a..z would strip each lowercase alphabetical
character. If charlist is not supplied, n, r, t, x0B, , and spaces are stripped.

trim function signature trim(string, charlist)


Argument Argument Meaning
string Mandatory. Specifies the string to check

charlist Not Mandatory. Specifies which characters to remove from the string. If left out, all of the following characters
are removed:

• “” – NULL
• “t” – tab
• “n” – new line
• “x0B” – vertical tab
• “r” – carriage return
• ” ” – ordinary white space

Code Example
<?php
$text = ('asdf This is a
cool string with some nonsense characters

at the start and end,

not to mention some really strange whitespace characters

asdf');

$slim_n_trim = trim($text, 'asdf');

echo $slim_n_trim;

?>

This is a cool string with some nonsense characters at the start and end, not to
mention some really strange whitespace characters

12. str_repeat() definition: The str_repeat() function repeats a string a specified


number of times..
Usage: Returns a string consisting of repeat copies of string appended to each other.
If repeat is not greater than 0, an empty string is returned.

str_repeat function signature substr(string, repeat)


Argument Argument Meaning

string Mandatory. Specifies the string to repeat


repeat Mandatory. Specifies the number of times the string will be repeated. Must be greater or equal to 0

Code Example
<?php
echo str_repeat('Everything is Awesome! ', 3);
?>

Everything is Awesome! Everything is Awesome! Everything is Awesome!

13. strtoupper() definition: The strtoupper() function returns a string with all of it’s
characters converted to uppercase.
Usage:If you know where the information that you want lies in a larger string, you can
extract it out with the strtoupper() function.

strtoupper function signature strtoupper(string)


Argument Argument Meaning

string Mandatory. Specifies the string to be converted to uppercase.

Code Example
<?php
$tired = "hey buddy, sorry I didn't get my caffeine yet";
$starbucks = ", but hold up - i'll drink some now.... ... ten minutes later...";
$awesome = strtoupper(" wow I feel awesome!!!");
echo $tired.$starbucks.$awesome;
?>

hey buddy, sorry I didn’t get my caffeine yet, but hold up – i’ll drink some now…. …
ten minutes later… WOW I FEEL AWESOME!!!

14. str_pad() definition: The str_pad() function pads a string to a new length.
Usage: Pads string using pad_string until it is at least length characters and returns the
resulting string. By specifying pad_type, you can control where the padding occurs..
str_pad function signature str_pad(string, length, pad_string, pad_type)
Argument Argument Meaning

string Mandatory. Specifies the string to pad

length Mandatory. Specifies the new string length. If this value is less than the original length of the string, nothing will
be done

pad_string Not Mandatory. Specifies the string to use for padding. Default is whitespace

pad_type Not Mandatory. Specifies what side to pad the string.

Possible values:

• STR_PAD_BOTH – Pad to both sides of the string. If not an even number, the right side gets the extra
padding
• STR_PAD_LEFT – Pad to the left side of the string
• STR_PAD_RIGHT – Pad to the right side of the string. This is default

Code Example
<?php
echo str_pad('Microsoft owns Minecraft ', 53, 'wow!');
?>

Microsoft owns Minecraft wow!wow!wow!wow!wow!wow!wow!

15. ord() definition: The ord() function returns the ASCII value of the first character of a
string.
Usage: Returns the ASCII value of the first character in string.

ord function signature ord(string)


Argument Argument Meaning

string Mandatory. The string to get an ASCII value from

Code Example
<?php
$one = ord('The best way to get an iPhone is to visit your friendly Apple Store');
$two = ord('t');
$three = ord('Hello there good buddy');

echo "$one | $two | $three";


?>

84 | 116 | 72

16. strtok() definition: The strtok() function splits a string into smaller strings called
tokens.
Usage: Breaks string into tokens separated by any of the characters in split and returns the
next
token found. The first time you call strtok() on a string, use the first function prototype;
afterward, use the second, providing only the tokens. The function contains an internal
pointer for each string it is called with.

strtok function signature strtok(string, split) and strtok(split)


Argument Argument Meaning

string Mandatory. Specifies the string to split

split Mandatory. Specifies one or more split characters

Code Example
<?php
$string = "Please make sure to follow the instructions (or you'll be put to sleep).";
$token = strtok($string, " ");

while ($token !== false)


{
echo "$token<br>";
$token = strtok(" ");
}
?>

Please
make
sure
to
follow
the
instructions
(or
you’ll
be
put
to
sleep).

17. strtr() definition: The strtr() function translates certain characters in a string.
Usage: When given three arguments, returns a string created by translating in string every
occurrence of a character in from to the character in to with the same position. When
given two arguments, returns a string created by translating occurrences of the keys
in array in string with the corresponding values in array.

strtr function signature strtr(string, from, to) and strtr(string, array)


Argument Argument Meaning

string Mandatory. Specifies the string to translate

from Required (unless array is used). Specifies what characters to change

to Required (unless array is used). Specifies what characters to change into

array Required (unless to and from is used). An array containing what to change from as key, and what to change to as
value

Code Example
<?php
$array = array("tech" => "help", "support" => "right now");
echo strtr("Do you need some tech support?",$array);
?>

Do you need some help right now?


18. rtrim() definition: The rtrim() function removes whitespace or other predefined
characters from the right side of a string.
Usage:Returns string with all characters in charlist stripped from the end. If charlist is not
specified, the characters stripped are n, r, t, v, , and spaces..

rtrim function signature rtrim(string, charlist)


Argument Argument Meaning

string Mandatory. Specifies the string to check

charlist Not Mandatory. Specifies which characters to remove from the string. If left out, all of the following characters
are removed:

• “” – NULL
• “t” – tab
• “n” – new line
• “x0B” – vertical tab
• “r” – carriage return
• ” ” – ordinary white space

Code Example
<?php
$right_trimmed = rtrim('The prophecy states you are the most interesting person in the world.
cANyOUbELIEVEtHAT?', 'cANyOUbELIEVEtHAT?');
echo $right_trimmed;
?>

The prophecy states you are the most interesting person in the world.

19. md5() definition: The md5() function calculates the MD5 hash of a string.
Usage:Calculates the MD5 encryption hash of string and returns it. If the raw option
is true then the MD5 hash returned is in raw binary format (length of 16), binary defaults
to false, thus making MD5 return a full 32-character hex string.

md5 function signature md5(string, raw)


Argument Argument Meaning

string Mandatory. The string to be calculated


raw Not Mandatory. Specifies hex or binary output format:

• TRUE – Raw 16 character binary format


• FALSE – Default. 32 character hex number

Code Example
<?php
$str = "Soon, I will be a collection of characters you could never possibly understand.";
echo md5($str);
?>

78e382eb9b9b8c265bb10d3bce8e1608

20. strrpos() definition: The strrpos() function finds the position of the last occurrence of
a string inside another string.
Usage:Returns the position of the last occurrence of find in string, or false if find is not
found.
If specified and positive, the search begins start characters from the start of string. If
specified and negative, the search begins start characters from the end of string.

strrpos function signature strrpos(string, find, start)


Argument Argument Meaning

string Mandatory. Specifies the string to search

find Mandatory. Specifies the string to find

start Not Mandatory. Specifies where to begin the search

Code Example
<?php
$position = strrpos("Everything is awesome, everything is cool when your part of a team, everything
is awesome, when you're living the dream!", "awesome");
echo "The last position of 'awesome' is at position $position";
?>

The last position of ‘awesome’ is at position 82


21. join() definition: The join() function returns a string from the elements of an array.
Usage: The join() function is simply an alias for implode().

join function signature join(separator, array)


Argument Argument Meaning

separator Not Mandatory. Specifies what to put between the array elements. Default is “” (an empty string)

array Mandatory. The array to join to a string

Code Example
<?php
$fields = array('This', 'does', 'the same', 'thing as implode()');
$string = join(' @@ ', $fields);

echo $string;
?>

This @@ does @@ the same @@ thing as implode()

22. bin2hex() definition: The bin2hex() function returns a part of a string.


Usage:Converts string to a hexadecimal (base-16) value. Up to a 32-bit number, or
2,147,483,647 decimal, can be converted.

bin2hex function signature bin2hex(string)


Argument Argument Meaning

string Mandatory. Specifies the string to be converted to hex

Code Example
<?php
$hex = bin2hex('I am now nothing more than hex');
echo $hex;
?>
4920616d206e6f77206e6f7468696e67206d6f7265207468616e20686578

23. ltrim() definition: The ltrim() function removes whitespace or other predefined
characters from the left side of a string.
Usage:Returns string with all characters in charlist stripped from the beginning.
If charlist is not specified, the characters stripped are n, r, t, v, , and spaces..

ltrim function signature ltrim(string, charlist)


Argument Argument Meaning

string Mandatory. Specifies the string to check

charlist Not Mandatory. Specifies which characters to remove from the string. If left out, all of the following characters
are removed:

• “” – NULL
• “t” – tab
• “n” – new line
• “x0B” – vertical tab
• “r” – carriage return
• ” ” – ordinary white space

Code Example
<?php
$left_trimmed = ltrim('cANyOUbELIEVEtHAT? The prophecy states you are the most interesting person in
the world. ', 'cANyOUbELIEVEtHAT?');
echo $left_trimmed;
?>

The prophecy states you are the most interesting person in the world.

24. substr_replace() definition: The substr_replace() function replaces a part of a


string with another string.
Usage:Replaces a substring in string with replacement. The substring replaced is selected
using the same rules as those of substr(). If string is an array, replacements take place on
each string within the array. In this case, replacement, start, and length can either be
scalar values, which are used for all strings in string, or arrays of values to be used for
each corresponding value in string.
substr_replace function signature substr_replace(string, replacement, start, length)
Argument Argument Meaning

string Mandatory. Specifies the string to check

replacement Mandatory. Specifies the string to insert

start Mandatory. Specifies where to start replacing in the string

• A positive number – Start replacing at the specified position in the string


• Negative number – Start replacing at the specified position from the end of the string
• 0 – Start replacing at the first character in the string

length Not Mandatory. Specifies how many characters should be replaced. Default is the same length as the string.

• A positive number – The length of string to be replaced


• A negative number – How many characters should be left at end of string after replacing
• 0 – Insert instead of replace

Code Example
<?php
$greet = "Goooooood Morning Vietnam!";
$nyc = substr_replace($greet, "New York!", 18, 7);

echo $nyc.'<br>';

$boston = substr_replace($nyc, "Boston", 18, 8);

echo $boston;
?>

Goooooood Morning New York!!


Goooooood Morning Boston!!

25. str_split() definition: The str_split() function splits a string into an array.
Usage: Splits string into an array of characters, each containing length characters;
if length is not specified, it defaults to 1.
str_split function signature str_split(string, start, length)
Argument Argument Meaning

string Mandatory. Specifies the string to split

length Not Mandatory. Specifies the length of each array element. Default is 1

Code Example
<?php
print_r(str_split('SPACESHIP!'));
?>

Array
(
[0] => S
[1] => P
[2] => A
[3] => C
[4] => E
[5] => S
[6] => H
[7] => I
[8] => P
[9] => !
)

26. sha1() definition: The sha1() function returns a part of a string.


Usage: Calculates the sha1 encryption hash of string and returns it. If raw is set and is true,
the
raw binary is returned instead of a hex string.

sha1 function signature sha1(string, raw)


Argument Argument Meaning

string Mandatory. The string to be calculated


raw Not Mandatory. Specify hex or binary output format:

• TRUE – Raw 20 character binary format


• FALSE – Default. 40 character hex number

Code Example
<?php
$password = sha1('password');

echo "Hey bud, what's your password? You: Oh it's $password. - Let me know if you have any trouble
logging in.";

?>

Hey bud, what’s your password? You: Oh it’s


5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8. – Let me know if you have any
trouble logging in.

27. ucfirst() definition: The ucfirst() function returns a part of a string.


Usage:Returns string with the first character, if alphabetic, converted to uppercase. The
table used for converting characters is locale-specific.

ucfirst function signature ucfirst(string)


Argument Argument Meaning

string Mandatory. Specifies the string to apply an uppercase first letter to.

Code Example
<?php
$lcfirst = "super cool";

$ucfirst = ucfirst($lcfirst);

echo $ucfirst;
?>

Super cool
28. chunk_split() definition: The chunk_split() function splits a string into a series of
smaller parts.
Usage:If you know where the information that you want lies in a larger string, you can
extract it out with the chunk_split() function.

chunk_split function signature chunk_split(string, length, end)


Argument Argument Meaning

string Mandatory. Specifies the string to split

length Not Mandatory. A number that defines the length of the chunks. Default is 76

end Not Mandatory. A string that defines what to place at the end of each chunk. Default is rn

Code Example
<?php
$sentence = "Eat the Leafy Greens for good health.";

$chunked = chunk_split($sentence, 3, ':-)');

echo $chunked;
?>

Eat:-) th:-)e L:-)eaf:-)y G:-)ree:-)ns :-)for:-) go:-)od :-)hea:-)lth:-).:-)

29. ucwords() definition: The ucwords() function converts the first character of each
word in a string to uppercase.
Usage:If you’d like to turn the first character of every word into uppercase, this function will
do that for you.

ucwords function signature ucwords(string)


Argument Argument Meaning

string Mandatory. Specifies the string to convert to uppercase for the first character of each word.

Code Example
<?php
$title = "ten reasons to check out the latest article on something!";

$titlized = ucwords($title);

echo $titlized;
?>

Ten Reasons To Check Out The Latest Article On Something!

30. htmlspecialchars() definition: The htmlspecialchars() function converts some


predefined characters to HTML entities.
Usage: When you need to convert actual HTML into the entities that make up that HTML,
this function can do that for you.

htmlspecialchars function signature htmlspecialchars(string, flags, character-set, double_encode)


Argument Argument Meaning

string Mandatory. Specifies the string to convert

flags Not Mandatory. Specifies how to handle quotes, invalid encoding and the used document type.

The available quote styles are:

• ENT_COMPAT – Default. Encodes only double quotes


• ENT_QUOTES – Encodes double and single quotes
• ENT_NOQUOTES – Does not encode any quotes

Invalid encoding:

• ENT_IGNORE – Ignores invalid encoding instead of having the function return an empty string.
Should be avoided, as it may have security implications.
• ENT_SUBSTITUTE – Replaces invalid encoding for a specified character set with a Unicode
Replacement Character U+FFFD (UTF-8) or &#FFFD; instead of returning an empty string.
• ENT_DISALLOWED – Replaces code points that are invalid in the specified doctype with a Unicode
Replacement Character U+FFFD (UTF-8) or &#FFFD;

Additional flags for specifying the used doctype:

• ENT_HTML401 – Default. Handle code as HTML 4.01


• ENT_HTML5 – Handle code as HTML 5
• ENT_XML1 – Handle code as XML 1
• ENT_XHTML – Handle code as XHTML
character-set Not Mandatory. A string that specifies which character-set to use.

Allowed values are:

• UTF-8 – Default. ASCII compatible multi-byte 8-bit Unicode


• ISO-8859-1 – Western European
• ISO-8859-15 – Western European (adds the Euro sign + French and Finnish letters missing in ISO-
8859-1)
• cp866 – DOS-specific Cyrillic charset
• cp1251 – Windows-specific Cyrillic charset
• cp1252 – Windows specific charset for Western European
• KOI8-R – Russian
• BIG5 – Traditional Chinese, mainly used in Taiwan
• GB2312 – Simplified Chinese, national standard character set
• BIG5-HKSCS – Big5 with Hong Kong extensions
• Shift_JIS – Japanese
• EUC-JP – Japanese
• MacRoman – Character-set that was used by Mac OS

Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1 in versions prior to
PHP 5.4. As of PHP 5.4, it will be ignored an replaced by UTF-8.

double_encode Not Mandatory. A boolean value that specifies whether to encode existing html entities or not.

• TRUE – Default. Will convert everything


• FALSE – Will not encode existing html entities

Code Example
<?php
$entity = htmlspecialchars('<b>Look at me, I am bold</b>. No, no actually you are not, you have been
special chared.');

echo $entity;
?>

<b>Look at me, I am bold</b>. No, no actually you are not, you have been special
chared.

31. stripos() definition: The stripos() function finds the position of the first occurrence of
a string inside another string.
Usage: Returns the position of the first occurrence of find in string using case-insensitive
comparison. If specified, the function begins its search at position start. Returns false
if find is not found.
stripos function signature stripos(string, find, start)
Argument Argument Meaning

string Mandatory. Specifies the string to search

find Mandatory. Specifies the string to find

start Not Mandatory. Specifies where to begin the search

Code Example
<?php
$string = 'Just where does that color appear in the string?';
$occurs = stripos($string,"COLOR");

echo "You're in luck because with stripos() I can tell you it is at $occurs";
?>

You’re in luck because with stripos() I can tell you it is at 21

32. substr_count() definition: The substr_count() function counts the number of


times a substring occurs in a string.
Usage: Returns the number of times substring appears in string. If start is provided, the
search begins at that character offset for at most length characters, or until the end of the
string if length is not provided.

substr_count function signature substr_count(string, substring, start, length)


Argument Argument Meaning

string Mandatory. Specifies the string to check

substring Mandatory. Specifies the string to search for

start Not Mandatory. Specifies where in string to start searching

length Not Mandatory. Specifies the length of the search


Code Example
<?php
$string = "Have you heard the news? Everyone’s talkin'
Life is good ‘cause everything awesome
Lost my job, there’s a new opportunity
More free time for my awesome community
I feel more awesome than an awesome possum
Dip my body in chocolate frostin'
Three years later wash off the frostin'
Smellin’ like a blossom, everything is awesome
Stepped in mud, got some new brown shoes
It’s awesome to win and it’s awesome to lose";

$awesome = substr_count($string, 'awesome');

echo "How about that, you said awesome $awesome times!";


?>

How about that, you said awesome 7 times!

33. number_format() definition: The number_format() function formats a number


with grouped thousands.
Usage:Creates a string representation of number. If decimals is given, the number is
rounded to that many decimal places; the default is no decimal places, creating an integer.
If decimalpoint and separator are provided, they are used as the decimal-place character
and thousands separator, respectively.

number_format function signature number_format(number, decimals, decimalpoint, separator)


Argument Argument Meaning

number Mandatory. The number to be formatted. If no other parameters are set, the number will be formatted
without decimals and with comma (,) as the thousands separator.

decimals Not Mandatory. Specifies how many decimals. If this parameter is set, the number will be formatted with a
dot (.) as decimal point

decimalpoint Not Mandatory. Specifies what string to use for decimal point

separator Not Mandatory. Specifies what string to use for thousands separator. Only the first character of separator is
used. For example, “xxx” will give the same output as “x”
Note: If this parameter is given, all other parameters are required as well

Code Example
<?php
$cash = 5500.257612345;

$savings = number_format($cash, 2);

echo "The company has $savings in reserve.";

?>

The company has 5,500.26 in reserve.

34. stripcslashes() definition: The stripcslashes() function removes backslashes


added by the addcslashes() function.
Usage: When you need to clean up data retrieved from a database or from an HTML form,
this function works great.

stripcslashes function signature stripcslashes(string)


Argument Argument Meaning

string Mandatory. Specifies the string to clean.

Code Example
<?php

$dirty = "Friend what you have is one dirty string";

$clean = stripcslashes($dirty);

echo $clean;
?>

Friend what you have is one dirty string

35. strstr() definition: The strstr() function searches for the first occurrence of a string
inside another string.
Usage: Returns the portion of string from the first occurrence of search until the end
of string, or from the first occurrence of search until the beginning
of string if before_search is specified
and true. If search is not found, the function returns false. If search contains more than
one character, only the first is used.

strstr function signature strstr(string, search, before_search)


Argument Argument Meaning

string Mandatory. Specifies the string to search

search Mandatory. Specifies the string to search for. If this parameter is a number, it will search for the character
matching the ASCII value of the number

before_search Not Mandatory. A boolean value whose default is “false”. If set to “true”, it returns the part of the string
before the first occurrence of the search parameter.

Code Example
<?php
$sentence = "PHP is a great open source software community.";

echo strstr($sentence, 'great');


?>

great open source software community.

36. wordwrap() definition: The wordwrap() function wraps a string into new lines when
it reaches a specific length.
Usage:Inserts break into string every width characters and at the end of the string and
returns the resulting string. While inserting breaks, the function attempts to not break in the
middle of a word. If not specified, break defaults to n and size defaults to 75. If cut is given
and is true, the string is always wrapped to the given width

wordwrap function signature wordwrap(string, width, break, cut)


Argument Argument Meaning

string Mandatory. Specifies the string to break up into lines


width Not Mandatory. Specifies the maximum line width. Default is 75

break Not Mandatory. Specifies the characters to use as break. Default is “n”

cut Not Mandatory. Specifies whether words longer than the specified width should be wrapped:

• FALSE – Default. No-wrap


• TRUE – Wrap

Code Example
<?php
$str = "Sometimes you will have a string that is quite long and in cases like that you can use the
wordwrap function to make it easier to work with.";
echo wordwrap($str,30,"<br>n");
?>

Sometimes you will have a


string that is quite long and
in cases like that you can use
the wordwrap function to make
it easier to work with.

37. addcslashes() definition: The addcslashes() function returns a string with


backslashes in front of the specified characters.
Usage:Returns escaped instances of characters in string by adding a backslash before
them. You
can specify ranges of characters by separating them with two periods; for example, to
escape characters between a and q, use "a..q". Multiple characters and ranges can be
specified in characters.

addcslashes function signature addcslashes(string, characters)


Argument Argument Meaning

string Mandatory. Specifies the string to be escaped

characters Mandatory. Specifies the characters or range of characters to be escaped

Code Example
<?php
$str = "Hi Traveler, thanks for stopping by!";
echo $str."<br>";
echo addcslashes($str,'t')."<br>";
echo addcslashes($str,'e')."<br>";

$str = "Green energy is getting more important everyday!";


echo $str."<br>";
echo addcslashes($str,'A..Z')."<br>";
echo addcslashes($str,'a..z')."<br>";
echo addcslashes($str,'a..g');
?>

Hi Traveler, thanks for stopping by!


Hi Traveler, thanks for stopping by!
Hi Traveler, thanks for stopping by!
Green energy is getting more important everyday!
Green energy is getting more important everyday!
Green energy is getting more important everyday!
Green energy is getting more important everyday!

38. parse_str() definition: The parse_str() function parses a query string into variables.
Usage: Parses string as if coming from an HTTP POST request, setting variables in the
local scope
to the values found in the string. If array is given, the array is set with keys and values
from the string.

parse_str function signature parse_str(string, array)


Argument Argument Meaning

string Mandatory. Specifies the string to parse

array Not Mandatory. Specifies the name of an array to store the variables. This parameter indicates that the
variables will be stored in an array.

Code Example
<?php
parse_str("color=Blue&make=Subaru&model=wrx");
echo $color."<br>";
echo $make."<br>";
echo $model;
?>

Blue
Subaru
wrx

39. strcmp() definition: The strcmp() function compares two strings.


Usage: Compares two strings; returns a number less than 0 if stringone is less than
stringtwo, 0 if the two strings are equal, and a number greater than 0 if stringone is greater
than stringtwo. The comparison is case sensitive meaning, “Alphabet” and “alphabet” are
not considered equal.

strcmp function signature strcmp(stringone, stringtwo)


Argument Argument Meaning

stringone Mandatory. Specifies the first string to compare

stringtwo Mandatory. Specifies the second string to compare

Code Example
<?php
echo strcmp("This is a string in PHP!", "This is a string in PHP!").' - ';
echo strcmp("Using strings in PHP is really great!", "PHP strings are fun!").' - ';
echo strcmp("Wow", "Look how easy it is to compare strings");
?>

0–1–1

40. strip_tags() definition: The strip_tags() function strips a string from HTML, XML,
and PHP tags.
Usage:Removes PHP and HTML tags from string and returns the result.
The allow parameter can
be specified to not remove certain tags. The string should be a comma-separated list of
the tags to ignore; for example, "<b>,<i>" will leave bold and italic tags.
strip_tags function signature strip_tags(string, allow)
Argument Argument Meaning

string Mandatory. Specifies the string to check

allow Not Mandatory. Specifies allowable tags. These tags will not be removed

Code Example
<?php
$markedup = '<h2>41. substr_compare() <small><strong>definition:</strong> The <code>substr()</code>
function returns a part of a string.</small></h2>';

$rawtext = strip_tags($markedup);

echo $rawtext;

?>

41. substr_compare() definition: The substr() function returns a part of a string.

41. substr_compare() definition: The substr_compare() function compares two


strings from a specified start position.
Usage: Compares stringone, starting at the position startpos, to stringtwo. If length is
specified, a maximum of that many characters are compared. Finally, if case is specified
and true, the comparison is case-insensitive. Returns a number less than 0 if the substring
of stringone is less than stringtwo, 0 if they are equal, and a number greater than 0 if the
substring of stringone is greater than stringtwo.

substr_compare function signature substr_compare(stringone, starttwo, startpos, length, case)


Argument Argument Meaning

stringone Mandatory. Specifies the first string to compare

stringtwo Mandatory. Specifies the second string to compare

startpos Mandatory. Specifies where to start comparing in string1. If negative, it starts counting from the end of the
string
length Not Mandatory. Specifies how much of string1 to compare

case Not Mandatory. A boolean value that specifies whether or not to perform a case-sensitive compare:

• FALSE – Default. Case-sensitive


• TRUE – Case-insensitive

Code Example
<?php
$equal = substr_compare("You won't believe it, but this comparison is equal", "comparison is equal",
31);

if($equal == 0){
echo 'The substrings are equal!';
}

?>

The substrings are equal!

42. setlocale() definition: The setlocale() function sets locale information which refers
to language, monetary, time and other information specific for a geographical area.
Usage:Sets the locale for constant functions to location. Returns the current location after
being set, or false if the location cannot be set. Any number of options for constant can
be added (or ORed) together.

setlocale function signature setlocale(constant, location)


Argument Argument Meaning

constant Mandatory. Specifies what locale information should be set.

Available constants:

• LC_ALL – All of the below


• LC_COLLATE – Sort order
• LC_CTYPE – Character classification and conversion (e.g. all characters should be lower or upper-case)
• LC_MESSAGES – System message formatting
• LC_MONETARY – Monetary/currency formatting
• LC_NUMERIC – Numeric formatting
• LC_TIME – Date and time formatting
location Mandatory. Specifies what country/region to set the locale information to. Can be a string or an array. It is
possible to pass multiple locations.

If the location is NULL or the empty string “”, the location names will be set from the values of
environment variables with the same names as the constants above, or from “LANG”.
If the location is “0”, the location setting is not affected, only the current setting is returned.
If the location is an array, setlocale() will try each array element until it finds a valid language or region
code. This is very useful if a region is known under different names on different systems.

Code Example
<?php
echo setlocale(LC_ALL, "US");
?>

English_United States.1252

43. str_ireplace() definition: The str_ireplace() function replaces some characters


with some other characters in a string.
Usage: Performs a case-insensitive search for all occurrences of find in string and replaces
them
with replace. If all three parameters are strings, a string is returned. If string is an array,
the
replacement is performed for every element in the array and an array of results is returned.
If find and replace are both arrays, elements in find are replaced with the elements
in replace with the same numeric indices. Finally, if find is an array and replace is a
string, any occurrence of any element in find is changed to replace. If supplied, count is
filled with the number of instances replaced.

str_ireplace function signature str_ireplace(find, replace, string, count)


Argument Argument Meaning

find Mandatory. Specifies the value to find

replace Mandatory. Specifies the value to replace the value in find

string Mandatory. Specifies the string to be searched

count Not Mandatory. A variable that counts the number of replacements


Code Example
<?php
$array = array("pretty neat", "mildy interesting", "really fun", "boring as ever");
print_r(str_ireplace("pretty neat", "wicked awesome", $array, $i));

echo "We made $i replacement!";


?>

Array
(
[0] => wicked awesome
[1] => mildy interesting
[2] => really fun
[3] => boring as ever
)
We made 1 replacements!

44. strncasecmp() definition: The strncasecmp() function compares two strings.


Usage: Compares two strings; returns a number less than 0 if stringone is less
than stringtwo, 0 if the two strings are equal, and a number greater than 0 if stringone is
greater than stringtwo. The comparison is case insensitive meaning, “Alphabet” and
“alphabet” are considered equal. This function is a case insensitive version of strcmp(). If
either string is shorter than length characters, the length of that string determines how
many characters are compared.

strncasecmp function signature strncasecmp(stringone, stringtwo, length)


Argument Argument Meaning

stringone Mandatory. Specifies the first string to compare

stringtwo Mandatory. Specifies the second string to compare

length Mandatory. Specify the number of characters from each string to be used in the comparison

Code Example
<?php
echo strncasecmp("Awesome", "Awesome",8);
echo "<br>";
echo strncasecmp("Awesome", "aWeSoMe",8);
?>

0
0

45. crypt() definition: The crypt() function returns a string encrypted using DES,
Blowfish, or MD5 algorithms.
Usage: Encrypts str using the DES encryption algorithm seeded with the two-character salt
value salt. If salt is not supplied, a random salt value is generated the first time crypt() is
called
in a script; this value is used on subsequent calls to crypt(). Returns the encrypted string.

crypt function signature crypt(str, salt)


Argument Argument Meaning

str Mandatory. Specifies the string to be encoded

salt Not Mandatory. A string used to increase the number of characters encoded, to make the encoding more
secure. If the salt argument is not provided, one will be randomly generated by PHP each time you call this
function.

Code Example
<?php
$secret = crypt('Password123', '$2a$10$1qAz2wSx3eDc4rFv5tGb5t');

echo "Can you guess what the characters of my password are? You can use $secret for a hint.";
?>

Can you guess what the characters of my password are? You can use
$2a$10$1qAz2wSx3eDc4rFv5tGb5eByw4KQDygkPgOmhrh8p0Ix50i4Pujwm for a
hint.

46. printf() definition: The printf() function outputs a formatted string.


Usage:Outputs a string created by using format and the given arguments. The arguments
are placed into the string in various places denoted by special markers in the format string.
Each marker starts with a percent sign (%) and consists of the following elements, in order.
Except for the type specifier, the specifiers are all optional. To include a percent sign in the
string, use %%.

printf function signature printf(format, arg1, arg2, arg++)


Argument Argument Meaning

format Mandatory. Specifies the string and how to format the variables in it.

Possible format values:

• %% – Returns a percent sign


• %b – Binary number
• %c – The character according to the ASCII value
• %d – Signed decimal number (negative, zero or positive)
• %e – Scientific notation using a lowercase (e.g. 1.2e+2)
• %E – Scientific notation using a uppercase (e.g. 1.2E+2)
• %u – Unsigned decimal number (equal to or greather than zero)
• %f – Floating-point number (local settings aware)
• %F – Floating-point number (not local settings aware)
• %g – shorter of %e and %f
• %G – shorter of %E and %f
• %o – Octal number
• %s – String
• %x – Hexadecimal number (lowercase letters)
• %X – Hexadecimal number (uppercase letters)

Additional format values. These are placed between the % and the letter (example %.2f):

• + (Forces both + and – in front of numbers. By default, only negative numbers are marked)
• ‘ (Specifies what to use as padding. Default is space. Must be used together with the width specifier.
Example: %’x20s (this uses “x” as padding)
• – (Left-justifies the variable value)
• [0-9] (Specifies the minimum width held of to the variable value)
• .[0-9] (Specifies the number of decimal digits or maximum string length)

Note: If multiple additional format values are used, they must be in the same order as above.

arg1 Mandatory. The argument to be inserted at the first %-sign in the format string

arg2 Not Mandatory. The argument to be inserted at the second %-sign in the format string

arg++ Not Mandatory. The argument to be inserted at the third, fourth, etc. %-sign in the format string

Code Example
<?php

$fahrenheit = 68;

$celsius = ($fahrenheit - 32) * 5 / 9;


printf("%.2fF is %.2fC", $fahrenheit, $celsius);
?>

68.00F is 20.00C

47.
quoted_printable_decode() definition: Thequoted_printable_decode() functio
n decodes a quoted-printable string to an 8-bit ASCII string.
Usage:Decodes string, which is data encoded using the quoted printable encoding, and
returns the resulting string.

quoted_printable_decode function signature quoted_printable_decode(string)


Argument Argument Meaning

string Mandatory. Specifies the quoted-printable string to be decoded

Code Example
<?php
$str = "Behold=0Athe=0AQuoted=0APrintable=0ADecode.";
echo quoted_printable_decode($str);
?>

Behold
the
Quoted
Printable
Decode.

48. sscanf() definition: The sscanf() function parses input from a string according to a
specified format.
Usage: The sscanf() function decomposes a string according to a printf()– like template

sscanf function signature sscanf(string, format, arg1, arg2, arg++)


Argument Argument Meaning
string Mandatory. Specifies the string to read

format Mandatory. Specifies the format to use.

Possible format values:

• %% – Returns a percent sign


• %c – The character according to the ASCII value
• %d – Signed decimal number (negative, zero or positive)
• %e – Scientific notation using a lowercase (e.g. 1.2e+2)
• %u – Unsigned decimal number (equal to or greather than zero)
• %f – Floating-point number
• %o – Octal number
• %s – String
• %x – Hexadecimal number (lowercase letters)
• %X – Hexadecimal number (uppercase letters)

Additional format values. These are placed between the % and the letter (example %.2f):

• + (Forces both + and – in front of numbers. By default, only negative numbers are marked)
• ‘ (Specifies what to use as padding. Default is space. Must be used together with the width specifier.
Example: %’x20s (this uses “x” as padding)
• – (Left-justifies the variable value)
• [0-9] (Specifies the minimum width held of to the variable value)
• .[0-9] (Specifies the number of decimal digits or maximum string length)

Note: If multiple additional format values are used, they must be in the same order as above.

arg1 Not Mandatory. The first variable to store data in

arg2 Not Mandatory. The second variable to store data in

arg++ Not Mandatory. The third, fourth, and so on, to store data in

Code Example
<?php
$string = "LenovotUltrabook (400)";
$a = sscanf($string, "%st%s (%d)");
print_r($a);
?>

Array
(
[0] => Lenovo
[1] => Ultrabook
[2] => 400
)
49. crc32() definition: The crc32() function calculates a 32-bit CRC (cyclic redundancy
checksum) for a string.
Usage: Calculates and returns the cyclic redundancy checksum (CRC) for string.

crc32 function signature crc32(string)


Argument Argument Meaning

string Mandatory. The string to be calculated

Code Example
<?php
$str = crc32("Eat Your Leafy Greens!");
printf("%un",$str);
?>

2184231086

50. htmlentities() definition: The htmlentities() function converts characters to


HTML entities.
Usage: Converts all characters in string that have special meaning in HTML and returns the
resulting string. All entities defined in the HTML standard are converted. If supplied, flags
determines the manner in which quotes are translated.

htmlentities function signature htmlentities(string, flags, character-set, double_encode)


Argument Argument Meaning

string Mandatory. Specifies the string to convert

flags Not Mandatory. Specifies how to handle quotes, invalid encoding and the used document type.

The available quote styles are:

• ENT_COMPAT – Default. Encodes only double quotes


• ENT_QUOTES – Encodes double and single quotes
• ENT_NOQUOTES – Does not encode any quotes
Invalid encoding:

• ENT_IGNORE – Ignores invalid encoding instead of having the function return an empty string.
Should be avoided, as it may have security implications.
• ENT_SUBSTITUTE – Replaces invalid encoding for a specified character set with a Unicode
Replacement Character U+FFFD (UTF-8) or &#FFFD; instead of returning an empty string.
• ENT_DISALLOWED – Replaces code points that are invalid in the specified doctype with a Unicode
Replacement Character U+FFFD (UTF-8) or &#FFFD;

Additional flags for specifying the used doctype:

• ENT_HTML401 – Default. Handle code as HTML 4.01


• ENT_HTML5 – Handle code as HTML 5
• ENT_XML1 – Handle code as XML 1
• ENT_XHTML – Handle code as XHTML

character-set Not Mandatory. A string that specifies which character-set to use.

Allowed values are:

• UTF-8 – Default. ASCII compatible multi-byte 8-bit Unicode


• ISO-8859-1 – Western European
• ISO-8859-15 – Western European (adds the Euro sign + French and Finnish letters missing in ISO-
8859-1)
• cp866 – DOS-specific Cyrillic charset
• cp1251 – Windows-specific Cyrillic charset
• cp1252 – Windows specific charset for Western European
• KOI8-R – Russian
• BIG5 – Traditional Chinese, mainly used in Taiwan
• GB2312 – Simplified Chinese, national standard character set
• BIG5-HKSCS – Big5 with Hong Kong extensions
• Shift_JIS – Japanese
• EUC-JP – Japanese
• MacRoman – Character-set that was used by Mac OS

Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1 in versions prior to
PHP 5.4. As of PHP 5.4, it will be ignored an replaced by UTF-8.

double_encode Not Mandatory. A boolean value that specifies whether to encode existing html entities or not.

• TRUE – Default. Will convert everything


• FALSE – Will not encode existing html entities

Code Example
<?php
$url = array(
'value' => urlencode('awesome')
);
$link = "http://vegibit.com/themes/vegitalian/index.php?var={$url['value']}";
$html = array(
'link' => htmlentities($link, ENT_QUOTES, 'UTF-8')
);
echo "<a href="{$html['link']}">Bootstrap Themes!</a>";
Bootstrap Themes!

51. levenshtein() definition: The levenshtein() function returns the Levenshtein


distance between two strings.
Usage: Calculates the Levenshtein distance between two strings. This is the number of
characters you have to replace, insert, or delete to transform stringone into stringtwo. By
default, replacements, inserts, and deletes have the same cost, but you can specify
different costs with insert, replace, and delete.

levenshtein function signature levenshtein(stringone, stringtwo, insert, replace, delete)


Argument Argument Meaning

stringone Mandatory. First string to compare

stringtwo Mandatory. Second string to compare

insert Not Mandatory. The cost of inserting a character. Default is 1

replace Not Mandatory. The cost of replacing a character. Default is 1

delete Not Mandatory. The cost of deleting a character. Default is 1

Code Example
<?php
$needtochange = levenshtein("Avenues", "Awesome");
echo "Avenues to Awesome has a Levenshtein distance of $needtochange";
?>

Avenues to Awesome has a Levenshtein distance of 5

52. strcasecmp() definition: The strcasecmp() function compares two strings.


Usage:Compares two strings; returns a number less than 0 if stringone is less
than stringtwo, 0 if the two strings are equal, and a number greater than 0 if stringone is
greater than stringtwo. The comparison is case insensitive meaning, “Alphabet” and
“alphabet” are considered equal.

strcasecmp function signature strcasecmp(stringone, stringtwo)


Argument Argument Meaning

stringone Mandatory. Specifies the first string to compare

stringtwo Mandatory. Specifies the second string to compare

Code Example
<?php
echo strcasecmp("Awesome", "Awesome");
echo "<br>";
echo strcasecmp("AwEsOmE", "awesome");
?>

0
0

53. strcspn() definition: The strcspn() function returns the number of characters
(including whitespaces) found in a string before any part of the specified characters are found.
Usage:Returns the length of the subset of string starting at start, examining a maximum
of length characters, to the first instance of a character from char.

strcspn function signature strcspn(string, char, start, length)


Argument Argument Meaning

string Mandatory. Specifies the string to search

char Mandatory. Specifies the characters to search for

start Not Mandatory. Specifies where in string to start


length Not Mandatory. Specifies the length of the string (how much of the string to search)

Code Example
<?php
$letters = strcspn("Solid State Storage!", "!");
echo "There are $letters letters before the exclamation point.";
?>

There are 19 letters before the exclamation point.

54. strripos() definition: The strripos() function finds the position of the last occurrence
of a string inside another string.
Usage: Returns the position of the last occurrence of find in string using a case-insensitive
search,
or false if find is not found. If specified and positive, the search begins start characters
from the start of string. If specified and negative, the search begins start characters from
the end of string. This function is a case-insensitive version of strrpos().

strripos function signature strripos(string, find, start)


Argument Argument Meaning

string Mandatory. Specifies the string to search

find Mandatory. Specifies the string to find

start Not Mandatory. Specifies where to begin the search

Code Example
<?php
$scooby = "Scooby Dooby Doo, Where are you Sooby Doo?";

$position = strripos("$scooby","doo");

echo "The last occurrence of 'doo' is at position $position."


?>

The last occurrence of ‘doo’ is at position 38.


55. strspn() definition: The strspn() function returns the number of characters found in the
string that contains only characters from the charlist parameter.
Usage: Returns the length of the substring in string that consists solely of characters
in charlist. If start is positive, the search starts at that character; if it is negative, the
substring starts at the character start characters from the string’s end. If length is given
and is positive, that many characters from the start of the substring are checked.
If length is given and is negative, the check ends length characters from the end of string.

strspn function signature strspn(string, charlist, start, length)


Argument Argument Meaning

string Mandatory. Specifies the string to search

charlist Mandatory. Specifies the characters to find

start Not Mandatory. Specifies where in the string to start

length Not Mandatory. Defines the length of the string

Code Example
<?php
$number = 777;
$isValidNumber = strspn($number, "1234567890") == strlen($number);

echo $isValidNumber;
?>

56. html_entity_decode() definition: The html_entity_decode()function converts


HTML entities to characters.
Usage: Converts all HTML entities in string to the equivalent character. All entities defined
in the HTML standard are converted. If supplied, flags determines the manner in which
quotes are translated. The possible values for flags are the same as those for htmlentities.
If supplied, character-set determines the final encoding for the characters. The possible
values for character-set are the same as those for htmlentities.
html_entity_decode function signature html_entity_decode(string, flags, character-set)
Argument Argument Meaning

string Mandatory. Specifies the string to decode

flags Not Mandatory. Specifies how to handle quotes and which document type to use.

The available quote styles are:

• ENT_COMPAT – Default. Decodes only double quotes


• ENT_QUOTES – Decodes double and single quotes
• ENT_NOQUOTES – Does not decode any quotes

Additional flags for specifying the used doctype:

• ENT_HTML401 – Default. Handle code as HTML 4.01


• ENT_HTML5 – Handle code as HTML 5
• ENT_XML1 – Handle code as XML 1
• ENT_XHTML – Handle code as XHTML

character- Not Mandatory. A string that specifies which character-set to use.


set
Allowed values are:

• UTF-8 – Default. ASCII compatible multi-byte 8-bit Unicode


• ISO-8859-1 – Western European
• ISO-8859-15 – Western European (adds the Euro sign + French and Finnish letters missing in ISO-
8859-1)
• cp866 – DOS-specific Cyrillic charset
• cp1251 – Windows-specific Cyrillic charset
• cp1252 – Windows specific charset for Western European
• KOI8-R – Russian
• BIG5 – Traditional Chinese, mainly used in Taiwan
• GB2312 – Simplified Chinese, national standard character set
• BIG5-HKSCS – Big5 with Hong Kong extensions
• Shift_JIS – Japanese
• EUC-JP – Japanese
• MacRoman – Character-set that was used by Mac OS

Code Example
<?php
$str = "<h1>©®™</h1>";
echo html_entity_decode($str);
?>

©®™
57. str_shuffle() definition: The str_shuffle() function randomly shuffles all the
characters of a string.
Usage: Rearranges the characters in string into a random order and returns the resulting
string.

str_shuffle function signature str_shuffle(string)


Argument Argument Meaning

string Mandatory. Specifies the string to shuffle

Code Example
<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

bfdaec

58. stristr() definition: The stristr()searches for the first occurrence of a string inside
another string.
Usage: This is the case insensitive version of strstr().

stristr function signature stristr(string, search, before_search)


Argument Argument Meaning

string Mandatory. Specifies the string to search

search Mandatory. Specifies the string to search for. If this parameter is a number, it will search for the character
matching the ASCII value of the number

before_search Not Mandatory. A boolean value whose default is “false”. If set to “true”, it returns the part of the string
before the first occurrence of the search parameter.

Code Example
<?php
$sentence = "PHP is a great open source software community.";

echo stristr($sentence, 'GrEaT');


?>

great open source software community.

59. strpbrk() definition: The strpbrk() function searches a string for any of the specified
characters.
Usage: Returns a string consisting of the substring of string, starting from the position of the
first instance of a character from charlist in string to the end of the string, or false if none
of the characters in charlist is found in string.

strpbrk function signature strpbrk(string, charlist)


Argument Argument Meaning

string Mandatory. Specifies the string to search

charlist Mandatory. Specifies the characters to find

Code Example
<?php
echo strpbrk("Jumping Jack Flash is a Gas!"," ");
?>

Jack Flash is a Gas!

60. strrev() definition: The strrev() function reverses a string.


Usage: If you need to know how to spell something backwards, this is the function for you..

strrev function signature strrev(string)


Argument Argument Meaning

string Mandatory. Specifies the string to reverse.


Code Example
<?php
$reverse = strrev('Awesome');

echo "Awesome spelled backwards is $reverse";


?>

Awesome spelled backwards is emosewA

61. addslashes() definition: The addslashes() function returns a string with backslashes
in front of predefined characters.
Usage:Returns escaped instances of characters in string by adding a backslash before
them. You can specify ranges of characters by separating them with two periods; for
example, to escape characters between b and o, use "b..o". Multiple characters and
ranges can be specified in characters.

addslashes function signature addslashes(string)


Argument Argument Meaning

string Mandatory. Specifies the string to be escaped.

Code Example
<?php
$str = addslashes('Tim said, "This is the best stuff so far"');
echo($str);
?>

Tim said, “This is the best stuff so far”

62. count_chars() definition: The count_chars() function returns information about


characters used in a string
Usage: Returns the number of occurrences of each byte value from 0–255
in string – mode determines the form of the result.
count_chars function signature count_chars(string, mode)
Argument Argument Meaning

string Required. The string to be checked

mode Not Mandatory. Specifies the return modes. 0 is default. The different return modes are:

• 0 – an array with the ASCII value as key and number of occurrences as value
• 1 – an array with the ASCII value as key and number of occurrences as value, only lists occurrences
greater than zero
• 2 – an array with the ASCII value as key and number of occurrences as value, only lists occurrences equal
to zero are listed
• 3 – a string with all the different characters used
• 4 – a string with all the unused characters

Code Example
<?php
$str = "How many times per week do you eat at Chipotle Mexican Grill?";
echo count_chars($str, 3);
?>

?CGHMacdehiklmnoprstuwxy

63. md5_file() definition: The md5_file() function calculates the MD5 hash of a file.
Usage:Calculates and returns the MD5 encryption hash for the file at file. An MD5 hash is a
32-character hexadecimal value that can be used to checksum a file’s data. If raw is
supplied and is true, the result is sent as a 16-bit binary value instead.

md5_file function signature substr(file, raw)


Argument Argument Meaning

file Mandatory. The file to be calculated

raw Not Mandatory. A boolean value that specifies hex or binary output format:

• TRUE – Raw 16 character binary format


• FALSE – Default. 32 character hex number

Code Example
<?php
$file = "somefile.txt";
$md5file = md5_file($file);
echo $md5file;
?>

453753ba5c6198a03deaa724b58c3eec

64. nl2br() definition: The nl2br() function inserts HTML line breaks (<br> or <br />) in
front of each newline (n) in a string.
Usage: If xhtml is true, then nl2br will use XHTML-compatible line breaks..

nl2br function signature nl2br(string, xhtml)


Argument Argument Meaning

string Mandatory. Specifies the string to check

xhtml Not Mandatory. A boolean value that indicates whether or not to use XHTML compatible line breaks:

• TRUE- Default. Inserts <br />


• FALSE – Inserts <br>

Code Example
<?php
echo nl2br("This is a piece of text on line 1.nYet this text is on line 2.");
?>

This is a piece of text on line 1.


Yet this text is on line 2.

65. sha1_file() definition: The sha1_file() function calculates the SHA-1 hash of a file.
Usage:Calculates and returns the sha1 encryption hash for the file at file. A sha1 hash is a
40-character hexadecimal value that can be used to checksum a file’s data. If raw is
supplied and is true, the result is sent as a 20-bit binary value instead.
sha1_file function signature sha1_file(file, raw)
Argument Argument Meaning

file Mandatory. The file to be calculated

raw Not Mandatory. A boolean value that specifies hex or binary output format:

• TRUE – Raw 20 character binary format


• FALSE – Default. 40 character hex number

Code Example
<?php
$file = "somefile.txt";
$sha1file = sha1_file($file);
echo $sha1file;
?>

f9515988673aae7dc5552d24c06ce947684c6bbb

66. str_word_count() definition: The str_word_count() function returns a part of a


string.
Usage: Counts the number of words in string using locale-specific rules. The value
of return dictates the returned value.

str_word_count function signature str_word_count(string, return, char)


Argument Argument Meaning

string Mandatory. Specifies the string to check

return Not Mandatory. Specifies the return value of the str_word_count() function.

Possible values:

• 0 – Default. Returns the number of words found


• 1 – Returns an array with the words from the string
• 2 – Returns an array where the key is the position of the word in the string, and value is the actual word

char Not Mandatory. Specifies special characters to be considered as words.


Code Example
<?php
$words = str_word_count("Super Mario is all you need to have a blast!");

echo "There are $words words in the sentence 'Super Mario is all you need to have a blast!"
?>

There are 10 words in the sentence ‘Super Mario is all you need to have a blast!

67. strnatcasecmp() definition: The strnatcasecmp() function compares two strings


using a natural order algorithm.
Usage: Compares two strings with case insensitivity and returns a number less than 0
if stringone is less than stringtwo, 0 if the two strings are equal, and a number greater
than 0 if stringone is greater than stringtwo.

strnatcasecmp function signature strnatcasecmp(stringone, stringtwo)


Argument Argument Meaning

stringone Mandatory. Specifies the first string to compare

stringtwo Mandatory. Specifies the second string to compare

Code Example
<?php
$firstarray = $secondarray = array(
"file1",
"file2",
"file10",
"file01",
"file100",
"file20",
"file30",
"file200"
);
echo "This sort uses standard ordering" . "<br />";
usort($firstarray, "strcmp");
print_r($firstarray);
echo "<br />";
echo "This uses the Natural Order" . "<br />";
usort($secondarray, "strnatcmp");
print_r($secondarray);
?>
This sort uses standard ordering
Array
(
[0] => file01
[1] => file1
[2] => file10
[3] => file100
[4] => file2
[5] => file20
[6] => file200
[7] => file30
)

This uses the Natural Order


Array
(
[0] => file01
[1] => file1
[2] => file2
[3] => file10
[4] => file20
[5] => file30
[6] => file100
[7] => file200
)

68. strnatcmp() definition: The strnatcmp() function compares two strings using a
natural order algorithm.
Usage: Compares two strings with case sensitivity and returns a number less than 0
if stringone is less than stringtwo, 0 if the two strings are equal, and a number greater
than 0 if stringone is greater than stringtwo.

strnatcmp function signature strnatcmp(string,start,length)


Argument Argument Meaning

stringone Mandatory. Specifies the first string to compare

stringtwo Mandatory. Specifies the second string to compare

Code Example
<?php
$firstarray = $secondarray = array(
"FilE1",
"fiLE2",
"filE10",
"fiLE01",
"fILe100",
"fIle20",
"File30",
"FIle200"
);
echo "This sort uses standard ordering" . "<br />";
usort($firstarray, "strcmp");
print_r($firstarray);
echo "<br />";
echo "This uses the Natural Order" . "<br />";
usort($secondarray, "strnatcmp");
print_r($secondarray);
?>

This sort uses standard ordering


Array
(
[0] => FIle200
[1] => FilE1
[2] => File30
[3] => fILe100
[4] => fIle20
[5] => fiLE01
[6] => fiLE2
[7] => filE10
)

This uses the Natural Order


Array
(
[0] => FIle200
[1] => FilE1
[2] => File30
[3] => fILe100
[4] => fIle20
[5] => fiLE01
[6] => fiLE2
[7] => filE10
)

69. strncmp() definition: The strncmp() function compares two strings.


Usage:This function works just like strcmp() function, except that strcmp() does not have
the length parameter.
strncmp function signature strncmp(stringone, stringtwo, length)
Argument Argument Meaning

stringone Mandatory. Specifies the first string to compare

stringtwo Mandatory. Specifies the second string to compare

length Mandatory. Specify the number of characters from each string to be used in the comparison

Code Example
<?php
$equal = strncmp("Awesome people do awesome things.", "Awesome birds fly fast.", 7);

$notequal = strncmp("Awesome people do awesome things.", "Awesome birds fly fast.", 9);

echo "Since $equal is equal, the value is $equal. Since $notequal is not equal, the value is
$notequal.";

?>

Since $equal is equal, the value is 0. Since $notequal is not equal, the value is 1.

70. chop() definition: The chop() function removes whitespaces or other predefined
characters from the right end of a string.
Usage: This works just like the rtrim() function.

chop function signature chop(string, charlist)


Argument Argument Meaning

string Mandatory. Specifies the string to check

charlist Not Mandatory. Specifies which characters to remove from the string.
The following characters are removed if the charlist parameter is empty:

• “” – NULL
• “t” – tab
• “n” – new line
• “x0B” – vertical tab
• “r” – carriage return
• ” ” – ordinary white space

Code Example
<?php
$chopped = rtrim('You really are the most interesting person in the world. cANyOUbELIEVEtHAT?',
'cANyOUbELIEVEtHAT?');
echo $chopped;
?>

You really are the most interesting person in the world.

The Ultimate PHP String Functions List Summary


If you made it to this point, pat yourself on the back. You are awesome! Studying this list of
PHP String Functions is a great way to learn your php string functions, or simply to keep
sharp. Remember, the most commonly used ones are at the top so the more of those near
the top that you can commit to memory, the better.

Autoloading For Code Organization

Autoloading helps us to organize our code in a clean fashion. This makes it


easier to understand how all of the pieces fit together. In fact, I would go as far
as to say that code organization is half the battle. With the introduction of
Composer to the PHP community, we now have a way to handle code
organization like never before. As we know, Composer is The Dependency
Manager for PHP. In addition to dependency management, Composer also
provides efficient autoloading for us. We’ll explore autoloading in this tutorial
now.

In our dependency injection for beginners tutorial, we built up a suite of classes to help us
win the FIFA Soccer world championship. We had a Country, some Players, a Team, and
many supporting methods and properties to accomplish our goal. We actually constructed
our little application in a very top down procedural style. That is to say, we had one big
PHP file that kind of looked like this.

• Class 1
• Class 2
• Class 3
• Client code / Implementation of classes.

This is perfect for learning and tutorial style applications. We can very quickly view
everything that is happening in one simple PHP file. If you would like to build a larger
application however, this approach will begin to fail pretty quickly. Maybe you have ten or
fifteen classes to account for, and many lines of code in your client to implement. One PHP
file is not going to cut it in this case. The convention is actually to create one class per
PHP file. From there, your client can either include the needed classes or autoload them
for use. Let’s try to break our prior application into a proper organization with autoloading.

The /root directory


We can start with the root directory. In this directory, we will have our client code in
the index.php file, in addition to a source directory which holds our classes. Inside
the source directory are the following three files.
/root/source/Country.php
<?php

class Country
{
protected $team;
protected $name;

public function __construct(Team $team, $name = 'USA')


{
$this->team = $team;
$this->name = $name;
}

public function recruit(Player $player)


{
$this->team->join($player);
}

/root/source/Player.php
<?php

class Player
{
protected $name;

public function __construct($name)


{
$this->name = $name;
}
}

/root/source/Team.php
<?php

class Team
{
protected $players = [];

public function __construct($players = [])


{
$this->players = $players;
}

public function join(Player $player)


{
$this->players[] = $player;
}

public function getplayers()


{
return $this->players;
}
}

/root/index.php
In our root directory we also have our client code which looks like this.
<?php

$team = new Team;

$usa = new Country($team);


$player1 = new Player('Carli Lloyd');

$usa->recruit($player1);

$player2 = new Player('Morgan Brian');


$player3 = new Player('Ashlyn Harris');
$player4 = new Player('Tobin Heath');
$player5 = new Player('Alex Morgan');

$usa->recruit($player2);
$usa->recruit($player3);
$usa->recruit($player4);
$usa->recruit($player5);

echo '<pre>';
print_r($team->getplayers());

When we try to run our program, things are not looking good!
Fatal error: Class ‘Team’ not found in C:\wamp\www\root\index.php on line 3

include the Needed Class Files


You might be thinking, well that is an easy fix. We just need to include the needed class
files like so.
<?php

include('source/Country.php');
include('source/Player.php');
include('source/Team.php');

$team = new Team;

$usa = new Country($team);

$player1 = new Player('Carli Lloyd');

$usa->recruit($player1);

$player2 = new Player('Morgan Brian');


$player3 = new Player('Ashlyn Harris');
$player4 = new Player('Tobin Heath');
$player5 = new Player('Alex Morgan');

$usa->recruit($player2);
$usa->recruit($player3);
$usa->recruit($player4);
$usa->recruit($player5);

echo '<pre>';
print_r($team->getplayers());

When we run this, everything does work just fine.

There is a better way however, and that is to make use of autoloading with Composer.
Manually including files is not going to scale, and will lead to trouble down the line. Let’s
see how to fix this with Composer.

Autoload With Composer


From here on out, we’ll assume you already have Composer installed. If you don’t, go
ahead and install now before proceeding. With Composer installed, we can navigate to our
project root using the terminal. In our case that is C:\wamp\www\root> If you’ve never
used Composer before, simply type composer to see what is available to us.
C:\wamp\www\root>composer
______
/ ____/___ ____ ___ ____ ____ ________ _____
/ / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
/_/
Composer version 1.0-dev (39e6f51bef3a4b148d9f35a0ae7a082e9aed97f4) 2015-07-09 11:04:41

Usage:
command [options] [arguments]

Options:
--help (-h) Display this help message
--quiet (-q) Do not output any message
--verbose (-v|vv|vvv) Increase the verbosity of messages: 1 for normal output, 2 for more verbose
output and 3 for debug
--version (-V) Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
--no-interaction (-n) Do not ask any interactive question
--profile Display timing and memory usage information
--working-dir (-d) If specified, use the given directory as working directory.

Available commands:
about Short information about Composer
archive Create an archive of this composer package
browse Opens the package's repository URL or homepage in your browser.
clear-cache Clears composer's internal package cache.
clearcache Clears composer's internal package cache.
config Set config options
create-project Create new project from a package into given directory.
depends Shows which packages depend on the given package
diagnose Diagnoses the system to identify common errors.
dump-autoload Dumps the autoloader
dumpautoload Dumps the autoloader
global Allows running commands in the global composer dir ($COMPOSER_HOME).
help Displays help for a command
home Opens the package's repository URL or homepage in your browser.
info Show information about packages
init Creates a basic composer.json file in current directory.
install Installs the project dependencies from the composer.lock file if present, or falls
back on the composer.json.
licenses Show information about licenses of dependencies
list Lists commands
remove Removes a package from the require or require-dev
require Adds required packages to your composer.json and installs them
run-script Run the scripts defined in composer.json.
search Search for packages
self-update Updates composer.phar to the latest version.
selfupdate Updates composer.phar to the latest version.
show Show information about packages
status Show a list of locally modified packages
suggests Show package suggestions
update Updates your dependencies to the latest version according to composer.json, and
updates the composer.lock file.
validate Validates a composer.json

We need a composer.json before anything else, so that init command looks good to us.
This command will take you through the process of creating a project using a
composer.json file. For the purposes of this tutorial, it will create a lot you don’t need, so
once you have your composer.json, simply edit it so you only have an empty file containing
the { and } characters, then run composer install which will generate
the autoload.php file we need. In fact, a few things are now created in our project, let’s
see.
/root
Note we now have a vendor directory in our root.

/root/vendor
As well as a newly created autoload.php file

/root/vendor/composer
And finally, some various supporting files for Composer.

Behold! The Autoload File!


<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit8ba53b7977ed0d2d530d1c0d7714ddcf::getLoader();
Configure PSR4
We’re almost there. First we need to configure the composer.json file for PSR4
autoloading.
{
"autoload": {
"psr-4": {
"Myapp\\": "source"
}
}
}

Once you declare your namespace, you’ll need to run composer dump-autoload in order to
generate the proper autoloading files. Let’s see.
autoload_psr4.php
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
'Myapp\\' => array($baseDir . '/source'),
);

Include the Autoloader


Recall that the index.php file lives in the root of our project. Note that in a prior step, we
simply used three include statements to make use of the three classes we need to run our
application. At this point, we are no longer using multiple include statements, but we will
need to include the autoloader file just one time in our client code so that it will
automatically load any class we need. In addition, we will add use statements for the
Team, Country, and Player classes. We can update our client code like so.
<?php

require('vendor/autoload.php');

use Myapp\Team;
use Myapp\Country;
use Myapp\Player;

$team = new Team;


$usa = new Country($team);

$player1 = new Player('Carli Lloyd');

$usa->recruit($player1);

$player2 = new Player('Morgan Brian');


$player3 = new Player('Ashlyn Harris');
$player4 = new Player('Tobin Heath');
$player5 = new Player('Alex Morgan');

$usa->recruit($player2);
$usa->recruit($player3);
$usa->recruit($player4);
$usa->recruit($player5);

echo '<pre>';
print_r($team->getplayers());

This is perfect, but when we try to run our application, we get an error of: Fatal error:
Class ‘Myapp\Team’ not found in C:\wamp\www\root\index.php on line 9. This is
because we had set a namespace of Myapp. If we declare a namespace via PSR4, we
need to make sure to update our class files to make use of those namespaces.

Update Class Namespaces


This is super easy. All we have to do is add namespace Myapp; to the top of our Class files.
/root/source/Country.php
<?php

namespace Myapp;

class Country
{
protected $team;
protected $name;

public function __construct(Team $team, $name = 'USA')


{
$this->team = $team;
$this->name = $name;
}

public function recruit(Player $player)


{
$this->team->join($player);
}

}
/root/source/Player.php
<?php

namespace Myapp;

class Player
{
protected $name;

public function __construct($name)


{
$this->name = $name;
}
}

/root/source/Team.php
<?php

namespace Myapp;

class Team
{
protected $players = [];

public function __construct($players = [])


{
$this->players = $players;
}

public function join(Player $player)


{
$this->players[] = $player;
}

public function getplayers()


{
return $this->players;
}
}
Now, when we run the client code, we are right back to our championship winning ways.

Composer Autoloading Summary


Composer is the best thing in the world for PHP developers. In this tutorial, we took a look
at just one aspect of what makes Composer so great, and that is it’s ability to generate
robust autoloading components for your application. With this newfound skill, you can
better organize and scale your applications no matter how many class dependencies it
might have.

PHP Simple HTML DOM Parser vs


FriendsOfPHP Goutte
In this tutorial, we’ll examine how the PHP Simple HTML DOM Parser
compares to the powerful FriendsOfPHP Goutte. In the early days, the PHP
Simple HTML DOM Parser was all we had to work with concerning data
extraction from HTML. Now that we have FriendsOfPHP Goutte, there is a
more feature rich way of doing this type of work. Before you get going, you’ll
need to configure a few things to get PHP Simple HTML DOM Parser,
FriendsOfPHP Goutte, and Guzzle PHP HTTP client up and running. This is
super easy to do thanks to Composer. Create a directory on your computer
called guzzle. CD into that directory and place this composer.json in it.
{
"require": {
"guzzlehttp/guzzle": "~6.0",
"emanueleminotto/simple-html-dom": "^1.5",
"fabpot/goutte": "^3.1"
}
}

Run composer install and or composer update from the command line. Everything will get
set up for you. Now you can simply place an index.php file in this directly and test out any
of the code we discuss in this tutorial. Your boilerplate in the index.php will look something
like this, make sure not to forget to require the autoload file that composer creates for you.
<?php

require 'vendor/autoload.php';

use Goutte\Client;
// Create a new Goutte client instance
$client = new Client();

// Hackery to allow HTTPS


$guzzleclient = new \GuzzleHttp\Client([
'timeout' => 60,
'verify' => false,
]);

// Hackery to allow HTTPS


$client->setClient($guzzleclient);

We set this up so you won’t get any errors like “cURL error 60: SSL certificate problem:
unable to get local issuer certificate”. If you do not set up your client like above, you may
get these errors!

Get HTML Elements

Get HTML Elements (PHP Simple HTML DOM Parser)


When you start with PHP Simple HTML DOM Parser, they will have you doing something
like this. In this case, you store some HTML into a variable, then find the value of the src
attribute of all image tags, along with finding the value of all href attributes of any links on
the page.
<?php

// Create DOM from URL or file


$html = file_get_html('https://www.facebook.com');

// Find all images


foreach ($html->find('img') as $element) {
echo $element->src . '<br>';
}

// Find all links


foreach ($html->find('a') as $element) {
echo $element->href . '<br>';
}

Get HTML Elements (FriendsOfPHP Goutte)


<?php

// Make a GET request (Create DOM from URL or file)


$crawler = $client->request('GET', 'https://www.facebook.com');
// Filter the DOM by calling an anonymous function on each node (Find all images)
$crawler->filter('img')->each(function ($node) {
echo $node->attr('src') . '<br>';
});

// (Find all links)


$crawler->filter('a')->each(function ($node) {
echo $node->attr('href') . '<br>';
});

As we see above, the PHP Simple HTML DOM Parser Library makes use of
a find() method, whereas in FriendsOfPHP Goutte you will typically be making use of
a filter() method to find elements in the DOM. Here are the function signatures for both
of these methods.

find(string $selector [, int $index]) Find elements by the CSS selector. Returns the Nth
Return type may vary. element object if index is set, otherwise return an array of
objects.

filter(string $selector) Filters the list of nodes with a CSS selector.


Always returns a public Crawler instance.

note: The find() method varies on what it returns to you based on the parameters you pass
in to it. This can sometimes lead to confusion. On the other hand, the filter() method
always returns a Symfony Crawler instance.

Modify HTML Elements

Modify HTML Elements (PHP Simple HTML DOM Parser)


<?php

$html = file_get_html('https://httpbin.org');

foreach ($html->find('title') as $element) {


echo $element->plaintext;
// httpbin(1): HTTP Client Testing Service
}

$html->find('title', 0)->innertext = 'Made with PHP Simple HTML DOM Parser!';

foreach ($html->find('title') as $element) {


echo $element->plaintext;
// Made with PHP Simple HTML DOM Parser!
}
Modify HTML Elements (FriendsOfPHP Goutte)
FriendsOfPHP Goutte actually recommends not to modify the DOM with their software.
While possible, the DomCrawler component is not designed for manipulation of the DOM or re-
dumping HTML/XML.
Therefore, we will not try to modify the DOM, but this is how you would fetch the title as
above with Goutte.
<?php

$crawler = $client->request('GET', 'https://httpbin.org');

$crawler->filter('title')->each(function ($node) {
echo $node->text() . '<br>';
// httpbin(1): HTTP Client Testing Service
});

Extract contents from HTML


Extract contents from HTML (PHP Simple HTML DOM Parser)
<?php

$html = file_get_html('https://httpbin.org');

foreach ($html->find('li') as $li) {


echo $li->plaintext . '<br>';
}

Extract contents from HTML (FriendsOfPHP Goutte)


<?php

$crawler = $client->request('GET', 'https://httpbin.org');

$crawler->filter('li')->each(function ($node) {
echo $node->text() . '<br>';
});
Result of each test.

Pretty straightforward stuff here. As we can see, the FriendsOfPHP Goutte versions are
typically a little more modern and elegant in their syntax thanks to the use of
their each() function which makes it really easy to iterate over every element with an
anonymous function.

How to find HTML elements


Really the bread and butter of how these libraries work is via their ability to fetch elements
from the DOM using standard CSS Selectors. Here we test almost all of the CSS
selectors available, except for the ones that only make sense in the context of an actual
web browser. If you don’t see a particular selector in this table, it means it does not work in
either library. In testing all of these selectors, we found that Goutte has a larger and more
feature rich set of CSS selection options. You can make use of this reference list of CSS
selectors that work with Goutte and Simple HTML DOM.
CSS Selector Testing On filter() method of 1. Goutte and find() method of 2
HTML Dom Parser
Selector Format Example Example description

.class .bash Selects all elements with class=”bash”

#id #manpage Selects the element with id=”manpage”

* * Selects all elements

element li Selects all <li> elements

element, element a, h1 Selects all <a> elements and all <h1> elements

element element li a Selects all <a> elements inside <li> elements

element > element p > a Selects all <a> elements where the parent is a <p> element

element + element div + h1 Selects all <h1> elements that are placed immediately after <div> eleme

element1 ~ element2 p ~ h2 Selects every <h2> element that are preceded by a <p> element

[attribute] [href] Selects all elements with a href attribute

[attribute=value] [data-bare-link=true] Selects all elements with data-bare-link=”true”

[attribute~=value] [alt~=Fork] Selects all elements with a href attribute containing the word “Fork”

[attribute|=value] [id|=\-curl] Selects all elements with an id attribute value starting with “-curl”

[attribute^=value] a[href^="https"] Selects every <a> element whose href attribute value begins with “https

[attribute$=value] a[href$=".org"] Selects every <a> element whose href attribute value ends with “.org”

[attribute*=value] a[href*="bin"] Selects every <a> element whose href attribute value contains the subst
“bin”

:checked input:checked Selects every checked <input> element

:disabled input:disabled Selects every disabled <input> element

:empty div:empty Selects every <div> element that has no children (including text nodes)

:enabled input:enabled Selects every enabled <input> element (simply means one that does not
disabled attribute)
:first-child li:first-child Selects every <li> element that is the first child of its parent

:first-of-type p:first-of-type Selects every <p> element that is the first <p> element of its parent

:lang(language) p:lang(en) Selects every <p> element with a lang attribute equal to “en”

:last-child li:last-child Selects every <li> element that is the last child of its parent

:last-of-type li:last-of-type Selects every <li> element that is the last <li> element of its parent

:not(selector) :not(div) Selects every element that is not a <div> element

:nth-child(n) span:nth-child(2) Selects every <span> element that is the second child of its parent

:nth-last-child(n) span:nth-last-child(2) Selects every <span> element that is the second child of its parent, coun
from the last child

:nth-last-of-type(n) span:nth-last-of-type(2) Selects every <span> element that is the second <span> element of its p
counting
from the last child

:nth-of-type(n) span:nth-of-type(1) Selects every <span> element that is the first <span> element of its pare

:only-child span:only-child Selects every <span> element that is the only child of its parent

:root :root Selects the document’s root element

<?php

//---------------------------------------------------------
//---------------------------------------------------------
// .bash selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('.bash')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('.bash') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// #manpage selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('#manpage')->each(function ($node) {
echo $node->text() . '<br>';
});
// Simple HTML Dom
$html = file_get_html('https://httpbin.org');
foreach ($html->find('#manpage') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// * all elements selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('*')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('*') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// li selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('li')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('li') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// a,h1 selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('a,h1')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('a,h1') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// li a selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('li a')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('li a') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// p > a selector test

$crawler = $client->request('GET', 'https://httpbin.org');


$crawler->filter('p > a')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('p > a') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// div + h1 selector test
// Goutte
// note: In Goutte you must use chained method calls for this selector
// to work (->filter('div')->filter('h1'))
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('div')->filter('h1')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('div + h1') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// p ~ h2 selector test

$crawler = $client->request('GET', 'https://httpbin.org');


$crawler->filter('p ~ h2')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('p ~ h2') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// [data-bare-link=true] selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('[data-bare-link=true]')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('[data-bare-link=true]') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// [alt~=Fork] selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('[alt~=Fork]')->each(function ($node) {
echo $node->attr('alt') . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('[alt~=Fork]') as $node) {
echo $node->alt . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// [id|=\-curl] selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('[id|=\-curl]')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('[id|=\-curl]') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// a[href^="https"] selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('a[href^="https"]')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('a[href^="https"]') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// a[href$=".org"] selector test
// Goutte
$crawler = $client->request('GET', 'https://httpbin.org');
$crawler->filter('a[href$=".org"]')->each(function ($node) {
echo $node->text() . '<br>';
});

// Simple HTML Dom


$html = file_get_html('https://httpbin.org');
foreach ($html->find('a[href$=".org"]') as $node) {
echo $node->plaintext . '<br>';
}
//---------------------------------------------------------
//---------------------------------------------------------
// input:checked selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter('input:checked')->each(function ($node) {
echo $node->attr('value') . '<br>';
// Condo
});
//---------------------------------------------------------
//---------------------------------------------------------
// input:disabled selector test

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


$crawler->filter('input:disabled')->each(function ($node) {
echo $node->attr('name') . '<br>';
// job
});
//---------------------------------------------------------
//---------------------------------------------------------
// div:empty selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter('div:empty')->each(function ($node) {
echo $node->attr('id') . '<br>';
// notextbud
});
//---------------------------------------------------------
//---------------------------------------------------------
// input:enabled selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter('input:enabled')->each(function ($node) {
echo $node->attr('name') . '<br>';
// shelter
// shelter
// name
//
// state
// username
});
//---------------------------------------------------------
//---------------------------------------------------------
// li:first-child selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter('li:first-child')->each(function ($node) {
echo $node->text() . '<br>';
// Apples
// 1
// one
});
//---------------------------------------------------------
//---------------------------------------------------------
// p:first-of-type selector test

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


$crawler->filter('p:first-of-type')->each(function ($node) {
echo $node->text() . '<br>';
// This first paragraph has text.
// Do you speak English?
// Yum!
});
//---------------------------------------------------------
//---------------------------------------------------------
// p:lang(en) selector test

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


$crawler->filter('p:lang(en)')->each(function ($node) {
echo $node->text() . '<br>';
// Do you speak English?
});
//---------------------------------------------------------
//---------------------------------------------------------
// li:last-child selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter('li:last-child')->each(function ($node) {
echo $node->text() . '<br>';
// Blueberries
// 4
// four
});
//---------------------------------------------------------
//---------------------------------------------------------
// li:last-of-type selector test

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


$crawler->filter('li:last-of-type')->each(function ($node) {
echo $node->text() . '<br>';
// Blueberries
// 4
// four
});
//---------------------------------------------------------
//---------------------------------------------------------
// :not(div) selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter(':not(div)')->each(function ($node) {
echo $node->attr('type') . '<br>';
// This works, but returns too much data to put in a comment!
});
//---------------------------------------------------------
//---------------------------------------------------------
// span:nth-child(2) selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter('span:nth-child(2)')->each(function ($node) {
echo $node->text() . '<br>';
// Lego Dimensions
});
//---------------------------------------------------------
//---------------------------------------------------------
// span:nth-last-child(2) selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter('span:nth-last-child(2)')->each(function ($node) {
echo $node->text() . '<br>';
// Minecraft
});
//---------------------------------------------------------
//---------------------------------------------------------
// span:nth-of-type(1) selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter('span:nth-of-type(1)')->each(function ($node) {
echo $node->text() . '<br>';
// Star Wars
// Ha Ha!
// Contrived Markup!
});
//---------------------------------------------------------
//---------------------------------------------------------
// span:only-child selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter('span:only-child')->each(function ($node) {
echo $node->text() . '<br>';
// Contrived Markup!
});
//---------------------------------------------------------
//---------------------------------------------------------
// :root selector test
// Goutte
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
$crawler->filter(':root')->each(function ($node) {
echo $node->text() . '<br>';
// Works but too much output to comment!
});
//---------------------------------------------------------

Now, you’ll notice that the above testing references two target urls. One is
https://httpbin.org, which is a site dedicated to offering this type of testing playground. The
other is a file on a local server consisting of custom HTML markup for test purposes. If you
would like to complete the tests in your own environment as well, here is the markup for
http://localhost/guzzle/domtesting.php.
<html>
<head>
<meta charset="utf-8">
<title>HTML DOM Testing</title>
</head>

<body>
<a href="#">This is link one</a> <a class="simplehtmldom" href="#">This is link two</a> <a title="A
title!" href="#">This link has a title!</a>
<div>Hello Div One.</div>
<div id="hello">This div has an id of hello.</div>
<div id="friendsofphp">This div has an id of foo.</div>
<div class="simplehtmldom">This div has a class of simplehtmldom</div>
<img src="http://placehold.it/350x150"> <img title="placeholder" src="http://placehold.it/350x150">
<div id="levelone">
<div id="leveltwo">
<div id="levelthree">This div is nested three levels deep.</div>
</div>
</div>
<ul>
<li>Apples</li>
<li>Oranges</li>
<li>Bananas</li>
<li>Pineapples</li>
<li>Blueberries</li>
</ul>
<table width="100%" border="0">
<tr>
<th>Make</th>
<th>Model</th>
</tr>
<tr>
<td>Tesla</td>
<td>Roadster</td>
</tr>
<tr>
<td class="motorcycle">Alta Motors</td>
<td class="motorcycle">Redshift MX</td>
</tr>
</table>
<form action="domtesting.php">
<input type="checkbox" name="shelter" value="House">
I have a House<br>
<input type="checkbox" name="shelter" value="Condo" checked>
I have a Condo<br>
Name:
<input type="text" name="name">
<br>
Job:
<input type="text" name="job" disabled>
<br>
<input type="number" min="4" max="9" value="5">
State:
<input type="text" name="state" value="Massachusetts" readonly>
<br>
Username:
<input type="text" name="username" required>
<br>
<input type="submit" value="Submit">
</form>
<div>
<p></p>
<p>Text in a paragraph</p>
</div>
<div>
<p>This first paragraph has text.</p>
<p>Other text in a paragraph</p>
</div>
<div id="notextbud"></div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
<p lang="en">Do you speak English?</p>
<div> <span>Star Wars</span> <span>Lego Dimensions</span> <span>Minecraft</span> <span>Samsung</span>
</div>
<div>
<p>Yum!</p>
<p>Yo!</p>
<span>Ha Ha!</span> </div>
<div> <span>Contrived Markup!</span> </div>
<table width="100%" border="0" cellpadding="3" cellspacing="3" class="table table-bordered">
<tbody>
<tr>
<td width="50%">mixed find(string $selector [, int $index])</td>
<td width="50%">Find elements by the CSS selector. Returns the Nth element
<strong>object</strong> if <strong>index</strong> is set, otherwise return an <strong>array</strong>
of object. </td>
</tr>
<tr>
<td width="50%">public Crawler filter(string $selector) </td>
<td width="50%">Filters the list of nodes with a CSS selector. </td>
</tr>
</tbody>
</table>

</body>
</html>

All of the testing we have done so far really focuses on using CSS Selectors to query the
in memory DOM to get at the elements we’re looking for. One you have an element or
elements however, what can you do with them? Often times, you just want the actual data
contained in them in the form of text content. For example, you fetch a title tag, but what
you really want is the information that the title tag holds. For this you typically apply a
method to the DOM element(s) you have captured. In the case of Goutte, this means
simply adding ->text() to the captured element like we see in all of the examples so far.
Conversely, in Simple HTML DOM Parser, this is done with a property called plaintext.
You can do even more with Goutte too, such as logging in to a website, fetching links from
reddit, and more.

Other Symfony Crawler Methods


We know that when we pass in a simple selector to filter() we may find many elements in
the DOM of that type. In that case, we iterate over them with the each() method like we’ve
seen many times.
<?php

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


$crawler->filter('li')->each(function ($node) {
echo $node->text() . '<br>';
});

// Apples
// Oranges
// Bananas
// Pineapples
// Blueberries
// 1
// 2
// 3
// 4
// one
// two
// three
// four
We can be more specific by using other methods, let’s see how.

eq()
Here we make use of the eq() method to find an element at a specific position from within
the node list. Notice we no longer need to iterate over the collection using each().
<?php

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


echo $crawler->filter('li')->eq(1)->text();

// Oranges

slice()
In this example, we try out the slice() method before iterating over the results. We pass the
integers of 3 and 2 to the method. 3 indicates we start at offset 3, while 2 indicates we
want to capture 2 items from that given start point.
<?php

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


$crawler->filter('li')->slice(3, 2)->each(function ($node) {
echo $node->text() . '<br>';
});

// Pineapples
// Blueberries

reduce()
This example shows using the reduce() method to only return strings that are greater than
2 characters in length.
<?php

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


$crawler->filter('li')->reduce(function ($node) {
if (strlen($node->text()) > 2) {
echo $node->text() . '<br>';
}
});

// Apples
// Oranges
// Bananas
// Pineapples
// Blueberries
// one
// two
// three
// four

first()
<?php

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


echo $crawler->filter('li')->first()->text();

// Apples

last()
<?php

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


echo $crawler->filter('li')->last()->text();

// four

siblings()
This example is pretty cool. First, we reach in and grab the li at position 2 (this is
Bananas). Then, we call siblings() which gives us only the siblings of that element. Finally
we use each() to iterate over the result.
<?php

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


$crawler->filter('li')->eq(2)->siblings()->each(function ($node) {
echo $node->text() . '<br>';
});

// Apples
// Oranges
// Pineapples
// Blueberries

attr()
This is one of those bread and butter methods to make use of. In this example, we find the
one form on the page, then retrieve the value of the action attribute. We have been using
attr() throughout this tutorial, so it should be fairly second nature by now.
<?php

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


echo $crawler->filter('form')->attr('action');

// domtesting.php

nodeName()
Suppose you are filtering by a class name like so, but you need to find what tag this class
is assigned to. For this you can use the nodeName() method.
<?php

$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');


echo $crawler->filter('.motorcycle')->nodeName();

// td

html()
If you would like to access all of the HTML inside of a given element, you can use the
html() method.
<?php
$crawler = $client->request('GET', 'http://localhost/guzzle/domtesting.php');
echo $crawler->filter('form')->html();

// <input type="checkbox" name="shelter" value="House">


// I have a House<br><input type="checkbox" name="shelter" value="Condo" checked>
// I have a Condo<br>
// Name:
// <input type="text" name="name"><br>
// Job:
// <input type="text" name="job" disabled><br><input type="number" min="4" max="9" value="5">
// State:
// <input type="text" name="state" value="Massachusetts" readonly><br>
// Username:
// <input type="text" name="username" required><br><input type="submit" value="Submit">

selectLink()
By making use of the selectLink() method, you can actually navigate to the content you
wish to retrieve. In this example, we visit reddit, click on the ‘top’ link, and find the number
one post at the current time.
<?php

$crawler = $client->request('GET', 'http://reddit.com');


$link = $crawler->selectLink('top')->link();
$crawler = $client->click($link);

echo $crawler->filter('p.title')->first()->text();

// New York judge arrested by State Troopers for DUI on her way to court

PHP Simple HTML DOM Parser vs FriendsOfPHP Goutte Summary


This was a fun little tutorial that had a look at how to use both the Simple HTML DOM
Parser and Goutte. Although the Simple HTML DOM Parser was a pretty neat tool at the
time of it’s release, it is becoming very dated, and development has ceased. Goutte on the
other hand is made up of beautiful Symfony components which are actively maintained
and developed. In addition, Goutte is a much more feature rich and fun to use.

How To Compare Two Arrays of Data and


Calculate Position Differences
Sometimes we might want to compare two arrays of data, and determine the
positional difference of each value in the array from one to the next. One
example of such an application of this might be similar to what you see where a
website is keeping track of the position of a programming language for
instance. Consider the Tiobe Index which tracks the position of a programming
language from month to month. Another example of this type of scenario might
be something like http://stats.js.org. Let’s see how we can use PHP to calculate
two arrays of data to achieve a similar type of effect.

How to Calculate The Difference With Index Based Arrays


<?php

$oldarray = ['FreeCodeCamp', 'angular.js', 'd3', 'jquery', 'react', 'meteor'];


$newarray = ['jquery', 'VueJS', 'd3', 'meteor', 'FreeCodeCamp', 'angular.js', 'react'];

// start looping through the new array


for ($i = 0; $i < sizeof($newarray); $i++) {

// get currentiterationvalue
$currentiterationvalue = $newarray[$i];

// for each current index value, find the associated old index position
$oldposition = array_search($currentiterationvalue, $oldarray);

// if the current index value is not found, it means it is a new entry


if ($oldposition == false) {
echo $currentiterationvalue . ' gained ' . abs($i - sizeof($newarray)) . '<br>';
} else {
// otherwise, we find the difference of the value's current position versus
// it's old position
$difference = $oldposition - $i;
// now we just add some logic to echo out if the value gained, lost, or
// did not change
if ($difference > 0) {
echo $currentiterationvalue . ' gained ' . abs($difference) . '<br>';
} elseif ($difference < 0) {
echo $currentiterationvalue . ' lost ' . abs($difference) . '<br>';
} else {
echo $currentiterationvalue . ' did not change' . '<br>';
}
}
}

jquery gained 3
VueJS gained 6
d3 did not change
meteor gained 2
FreeCodeCamp gained 3
angular.js lost 4
react lost 2
So first off we have an old array of data. In it, we have various JavaScript libraries to work
with. In this first example, we can see it is a simple index based array. The algorithm so to
speak is to begin looping through the newest array of data. On each iteration of the loop,
we want to capture the current iteration value in a variable. With that, we can
use array_search to find this current value as it existed in the old array. Once we have that
information, we check to see if it is a new entry or not. If array_search returns false, then
we know we have a new entry in the new array. In this case, we just say that the new entry
gained whatever the absolute value is from the end of the new array. If array_search
returns an integer value, then we now have the position of the current iterating value in the
old array. With this, we can now set up the logic to see if the value has gained, lost, or not
changed when comparing it’s position in the new array versus the old array. As we can
see, when we run the code it calculates positional differences just like we wanted.

How to Calculate The Difference With Associative Arrays


What if the arrays we are dealing with are associative arrays and not simple index arrays?
In this case, almost everything is the same. What we will need to do in this case however
is to use the array_keys function to convert our associative arrays into index based arrays
before we apply the calculations. As we can see below, the code still gives us the results
we expect when starting with associative arrays rather than index based arrays.
<?php

$oldarray = [
'FreeCodeCamp' => 'one',
'angular.js' => 'two',
'd3' => 'three',
'jquery' => 'four',
'react' => 'five',
'meteor' => 'six',
];

$newarray = [
'jquery' => 'one',
'VueJS' => 'two',
'd3' => 'three',
'meteor' => 'four',
'FreeCodeCamp' => 'five',
'angular.js' => 'six',
'react' => 'seven',
];

$oldarray = array_keys($oldarray);
$newarray = array_keys($newarray);

for ($i = 0; $i < sizeof($newarray); $i++) {


$currentiterationvalue = $newarray[$i];
$oldposition = array_search($currentiterationvalue, $oldarray);
if ($oldposition == false) {
echo $currentiterationvalue . ' gained ' . abs($i - sizeof($newarray)) . '<br>';
} else {
$difference = $oldposition - $i;
if ($difference > 0) {
echo $currentiterationvalue . ' gained ' . abs($difference) . '<br>';
} elseif ($difference < 0) {
echo $currentiterationvalue . ' lost ' . abs($difference) . '<br>';
} else {
echo $currentiterationvalue . ' did not change' . '<br>';
}
}
}

jquery gained 3
VueJS gained 6
d3 did not change
meteor gained 2
FreeCodeCamp gained 3
angular.js lost 4
react lost 2
How To Compare Two Arrays of Data and Calculate Position Differences
Summary
This quick tip type tutorial had a look at how to compare two arrays of data and figure out
the differences of each value in the arrays. You may be able to find all kinds of interesting
applications of this approach.

How To Quickly Test PHP Snippets

Have you ever wanted to quickly test small PHP snippets of code, but you
became bogged down in opening up your favorite IDE, preparing a simple
test.php file, loading it in the browser, etc.? Sometimes, all you want to do is
quickly test some logic. Perhaps you’re even just browsing some of the
example snippets at the PHP online manual, and thought it might be nice to just
quickly run these examples and see them in action. Maybe you want to try
refactoring a few things and see how it goes. Sometimes, your everyday
workflow is overkill for these simple situations. There is a perfect solution for
you however, I give you: PHP Console!

Created by Jordi Boggiano


Now the PHP Console is created by Jordi Boggiano. Jordi is the creator of Composer.
Composer has single handedly revolutionized the PHP landscape, so we know this PHP
Console is a nice little piece of software. When you visit the github page, you will see there
are steps to install the php debug console and it is pretty straight forward.
Install The PHP Debug Console
For this example, we simply installed it in C:\wamp\www\console by typing composer require
seld/php-console from the www directory.

You can also find the console on packagist right here.

Testing PHP Console


Once we have the php console installed, we can test it out by
visiting http://localhost/console/vendor/seld/php-console/.

Cool! Note that you are given a simple text area where you can write some simple snippets
of PHP, then simply click the Try this! button to execute the code. Just above the text area
is the code result output. If you’re so lazy that you can’t even bring yourself to click a
button to run your code, you also have the option to press ctrl-enter to run your snippet.
It’s a great little learning tool to have, and a fantastic way to test out quick snippets of code
without all the overhead. Maybe you’re just learning about a specific function in PHP such
as the substr php function. Now you can test it out very easily. Let’s see!
Imagine this code.
<?php

echo substr('PHP console is great', 4).'<br>';

Off the top of your head, you probably forget what this even does. No problem, plug it into
the console and test it out.

Maybe you’d like to put the array_unique function to the test. Also, very easy to do. First
let’s look at the code, then give it a test run in the PHP Console.
<?php

$array = [
'Time for a sandwich',
'Time for a sandwich',
'PHP 7 is great',
'PHP 7 is great',
'All about that bass, no treble',
'All about that bass, no treble',
];

$unique = array_unique($array);
foreach ($unique as $u) {
echo $u . '<br>';
}

We input the code into the text area and click Try It! Notice that the array_unique() function
does in fact remove any duplicates and the output looks good. How about creating our own
function right in the testing area. Will it work? Let’s try it out.
A very common thing in PHP is to check if a string contains a specific word. Said another
way, you will often need to check for the occurrence of one string inside of another.
The strpos() function can be used for this. Using this knowledge, let’s create a function that
is a little more user friendly. Here is the code we have come up with.
<?php

function findOccurrence($haystack, $needle)


{
if (strpos($haystack, $needle) !== false) {
return true;
} else {
return false;
}
}
$haystack = "We can find an occurrence of one string inside other";
$needle = "one string";

if (findOccurrence($haystack, $needle)) {
echo '<em>' . $needle . '</em> is in the haystack';
} else {
echo '<em>' . $needle . '</em> is not in the haystack';
}

We were able to create our own function named findOccurrence() which accepts
Pretty cool!
two parameters. The first is a haystack we will search through and the second is the
needle we will be looking for. Inside of our findOccurrence() function, we use strpos() to
do the heavy lifting for us. This is what is known as a wrapper function. We can make use
of wrappers to customize how we would like to interact with the language. In the example
above we can see that one string definitely does exist within the other string of We can find
an occurrence of one string inside other. Let’s change the needle we are looking for and
see what happens.

This time around we look for Gwen. When we run our function, we can see that it is
working correctly since it reports back to us that Gwen is not in the haystack. Shame, we
love Gwen.

What about connecting to a database?


When using the PHP Console tool, you can even connect to a database if you like to test
out snippets involving database queries. We have a database on the same localhost as
our PHP installation. The database name is “pdotest” and we’ll just log in as root with no
password. Let’s try it out!
<?php

$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');

var_dump($dbh);
Now that we know we can connect to the database, let’s try to create a table. The
database pdotest is currently empty, but we’ll create a table to hold a few links. Let’s
create a table in our database using PDO.
<?php

$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');

$sql = 'CREATE table links(ID INT(11) AUTO_INCREMENT PRIMARY KEY,


name VARCHAR( 50 ) NOT NULL, href VARCHAR( 50 ) NOT NULL);';

$results = $dbh->exec($sql);
var_dump($results);

With a table now created, we can complete an insert statement using PDO. Let’s insert a
link into our new table. We’ll insert a link for Google.
<?php

$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');

$sql = 'insert into links(name, href) values("Google", "http://google.com");';

$results = $dbh->exec($sql);
var_dump($results);
Now that we have inserted a link using PDO, let’s try to fetch it out of the database to see if
it worked. We’ll use a prepared statement to test this.
<?php

$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');

$statement = $dbh->prepare('select * from links');

$statement->execute();

var_dump($statement->fetchAll());

This seems to be working great! Let’s now add another link to the database, but
Pretty Cool!
this time we’ll make use of a prepared statement for the insert as well. We will add Twitter
this time.
<?php

$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');

$statement = $dbh->prepare('insert into links(name, href) values("Twitter", "http://twitter.com");');

$result = $statement->execute();

var_dump($result);
We get back a boolean true which means it worked. Let’s fetch the records again and see
what we get!

It definitely looks like it is working, but notice the duplication of data. This is because by
default, the fetchAll() method in PDO will return the data in two forms. One as an indexed
array, and another as an associative array. This actually works out pretty good, because it
gives you the flexibility to interact with that data however you might like. Another way to
make this work is to tell PDO that you would like objects to work with instead. Let’s see
how.
<?php

$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');

$statement = $dbh->prepare('select * from links');

$statement->execute();

var_dump($statement->fetchAll(PDO::FETCH_OBJ));
Now it would be easy for example to say you want the href of the second link in the
database. To do this, you could use this snippet in the php debug console.
<?php

$dbh = new PDO('mysql:host=localhost;dbname=pdotest', 'root', '');

$statement = $dbh->prepare('select * from links');

$statement->execute();

$results = $statement->fetchAll(PDO::FETCH_OBJ);

echo $results[1]->href;
PHP Psysh and Laravel Tinker
Another method of interacting with PHP at the console is via Psysh. If you use the Laravel
framework, you might be familiar with Tinker which is powered by Psysh. This tool is
officially a REPL or read eval print loop. It makes it possible for you to run PHP code
directly in the console. Let’s try setting up an index based array in Psysh(Tinker in this
case). Do note, that first you must enter the shell by typing php artisan tinker which will
give you the following output: Psy Shell v0.7.2 (PHP 7.0.5-3+donate.sury.org~trusty+1 —
cli) by Justin Hileman.
Now that we have a simple index based array of data, we can inspect it just like we would
expect. Here we test the data with a print_r() and var_dump() of the array.

Let’s test out the commonly used in_array() function which tests to see if a given value is in
an array.

Let’s now quickly create an object to work with in PHP. The quickest way to create an
object to work with in PHP without having to rely on a class is to simply cast an array to an
object. Let’s see how we might do this.

Notice that in this case we are simply assigning an associative array to a variable, but just
preceding the array brackets is the (object) cast to operator. This takes our associative
array and converts it to an object. Notice how it gets output to the screen right away. From
there, we can access individual properties of the object just like we normally would. All of
this is making use of the stdClass built in to PHP. We can even create a new class in the
REPL and test out its functionality. Let’s create a simple Task class right in the console
and complete a task.

Even though the repl only works one line at a time, you can still hit the enter key and go to
a new line, continuing to input code. What you will see is that the prompt changes from
three greater than signs to three dots. This indicates that the console recognizes you are
not finished entering valid PHP code, and you need to finish typing. The first example of
this is where we begin to define our Task class. Notice the three dots on each new line
right up until we finally complete the last closing brace of the class. At that point, null is
output to the screen and we get our standard prompt back. At this point, we have a new
class defined in memory. We can now make use of it! We create a new task to Clean
Desk. We then inspect the completed property and see that it is false. Then we make a call
to the finish() method and complete the task. A final inspection of the completed property
shows us that this is now true. Pretty cool! This type of simple test and run code at a
console is great practice to hone your syntax chops without the help of an IDE to guide you
along.

How To Quickly Test PHP Snippets Summary


In this tutorial we covered the php debug console. We found that it is a great tool to have
when you just want to test out quick snippets of PHP code. It makes the process easier
since you can avoid the overhead of firing up your IDE and switching between the IDE and
browser window along with the constant window refreshes. Sometimes you just want to
quickly test the behavior of any number of string functions, or array functions, test out
objects, or even work with a database like we did here. It’s a nice tool to have at your
disposal. Have fun!

Chapter 3: MySQL
Introduction to MySQL

MySQL is the world’s most popular open source database and powers all kinds
of different applications in the technology industry. Of course the blogging
platform WordPress uses MySQL as it’s database technology, but MySQL goes
far beyond just basic blog applications. Some of the biggest names in
technology today make use of MySQL, including Twitter, Facebook, Etsy, and
more. We also love working with MySQL when writing PHP either natively, or
with a great framework like Laravel or Codeigniter. These frameworks do a
great job of hiding away the details of how MySQL is working behind the
scenes. While this is great, it is really important to have a good grasp of the
fundamentals. This series of articles will do just that, dig into the nuts and bolts
of what MySQL is, how it works, and how we can leverage its power.

Working with MySQL at the command line


While applications like phpmyadmin, MySQL Workbench, and sequel pro are truly
excellent tools for working with MySQL, the best way to really dig into the technology is to
explore everything it has to offer right at the command line. Let’s have a look at our first
command.

show databases;
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| authdemo |
| blog |
| laratut |
| laravelblog |
| mysql |
| performance_schema |
| repotut |
| test |
| wordpress |
+--------------------+
10 rows in set (0.00 sec)

Congratulations! You just ran the first command of MySQL at the command line. Consider
it a hello world of sorts. In our output, we can see there are a bunch of databases already
present in this installation. Not to worry, we are going to be creating new databases and
tables from scratch.

Getting Your Hands Dirty With MySQL


The best option for learning MySQL is to of course have it installed on your local machine.
Whether you are on Mac, Linux, or Windows, there is an option for you. The example listed
above was at the command line of a local installation using wamp. For example if you are
accessing from a wamp install, you would click on the wamp task tray icon, then go
to MySQL->MySQL Console

Fantastic! You’re ready to start working with MySQL.


What if I don’t have MySQL Installed?
Like we said, it really is best if you install MySQL locally on your machine to work along
with the examples. In the rare instance that you don’t, you can still practice the MySQL
syntax online. In fact some of these tools will prove useful, even if you do have MySQL
installed locally but would like more options. You might be familiar with sites
like http://jsfiddle.net/ where you can quickly mock up some HTML and JavaScript to get
nice examples of code. You get to skip the whole process of booting up you local server,
opening your IDE and so on. Well did you know there is a great tool to do this as well with
MySQL? Behold, I give you…
http://sqlfiddle.com/
At this handy little website you can choose what type of database you’d like to work with,
you are not limited to just MySQL. For our purposes however, we will be using MySQL. To
get started, you can click ‘Build Schema’to get a session ready. You can then simply enter
your commands in the window on the right, then click ‘Run SQL’.

Nice! Plus one of the design of the site as well. They’re using the Bootstrap Framework
which we are also huge fans of.
http://demo.phpmyadmin.net/master-config/
Another option for working with MySQL if you do not have it installed locally is to visit the
demo page at the phpmyadmin website. Here you can use the SQL tab to run MySQL
commands all day long if you like. Once you test it out, if you like the UI, you can easily
download a copy for use in your own environment.

Database Terminology and High Level Overview


When we think of a database, one analogy is to use the database vs spreadsheet
comparison. While they are definitely not the same thing, they do share some similarities.
Let’s examine.

Similarities of Databases to Spreadsheets


• Data is stored in Columns and Rows
• Both can calculate new data based on existing data
• Both have Multi User Capabilities

Characteristics of Spreadsheets
Data is stored in Cells, which can also have built in calculation or formatting information.
You may be familiar with the fact that with a spreadsheet, there can be all kinds of markup
which decorates the data in various ways. Because of this reason, spreadsheets are a
meeting room favorite among the business world. In addition, any time you make an
operation on data within a spreadsheet, that operation creates more data. Because of this,
you will find that you can run into unwanted bloat as you add more and more calculations.
Characteristics of Databases
Databases on the other hand store their information in what we call a Record. The
database will store only the data and values. All formatting and calculations are applied
later. The analogy to MVC or model, view, controller kind of applies here in that just like in
web development where we try to separate out logic from markup, it makes sense as well
to keep formatting and actual data separated with our databases. With databases, when
you perform calculations, sorting and so on, these data operations take place only after the
data has been retrieved. This allows you to display only the result of said calculations,
rather than having to store the result as well. A huge benefit of working with a database is
that you can eliminate duplicate information.

Databases are Efficient Mechanisms of Storage


In summary, we can now see why it is great to use databases for the persistence layer in
our web applications. Databases allow us to specify a type for our data as well as
providing the ability to eliminate redundancy and formatting differences. Databases are
also less error prone, and are not effected by users performing various sorting on the data
which might break data associations within a spreadsheet for example. There is a fair
amount of effort involved in truly understanding how databases work, but it is well worth
the effort.

Flat Files and Relational Databases


Believe it or not, flat files are a very efficient means of storing and accessing data. Flat files
can easily show and manipulate data, and they also have the added benefit that stored
data does not change when calculations are done after data retrieval. Flat files also have
powerful approaches to deal with filtering and matching operations. Text files however do
not have data types. You might use something like a tab character, or comma to separate
fields. This is fine, yet it puts the burden of enforcing the distinction between fields squarely
on your shoulders, and who wants that? Text file and Flat file are basically the same thing,
just a different way of defining them.
Databases on the other hand provide the ability to assign a type to any data you store
within it. The idea of data types in MySQL is very important, especially when we are using
a programming language to interact with our database. You may want to store real
numbers, integers, dates, times, and so on. Databases give you this very thing. In addition,
when data is stored in the database, all data is kept separated from display. This helps to
eliminate duplicate information and data bloat. Flat files are great for some simple
applications but databases are the more powerful tool to employ when you need to have
greater control over your data.

Database Normalization
When working with databases, you’ll often run into the term, Normalization. More
specifically, we’re talking about how to organize fields and tables within the database. For
example, which fields should belong to which tables? Database normalization is the
process of deciding how to organize the data in order to make querying the database at a
later time more efficient. The goal is to organize the tables and fields in the database to
reduce as much as possible any dependency or redundancy. The objective is to isolate
data so that any additions, deletions, or modifications of a field can be made in just one
table and then propagated through the rest of the database using the defined relationships.
This is part of the reason for calling it a relational database.
Forms of Normalization
Third normal form, or 3NF, is the standard to which database design best practices adhere
to. Third normal form includes the First Normal Form as well as the Second Normal Form.
In order to understand 3NF, we’ll have to first observe 1NF and 2NF.
First Normal Form: First normal form is the idea that there is a single value for each field.
Second Normal Form: The table must first be in 1NF, as well as the fact that all of the
information in the table is dependent on what defines the row.
Third Normal Form: The table must first be in 1NF, and 2NF. All of the non defining fields
must be directly dependent on the defining fields.
Beyond the academic definitions of the various forms of normalization, is a key concept to
take away. When designing your database schema, you want to keep your tables as
concise as you possibly can, and may need to break apart tables that have too many fields
into two or more tables with a relation defined. This is the tricky part of learning the ins and
outs of a relational database but once we have a good understanding of database
normalization, we’ll be on our way to better database design.
Acronyms upon Acronyms
As if you didn’t have enough acronyms to keep up with in your day to day life as a web
developer, we’ll be adding a few more to your toolkit for working with databases. Here are
the most common you’ll come across.
• DB: Database
• RDBMS: Relational Database Management System – A relational database
management system is a database management system that is based on the
relational model as introduced by E. F. Codd of IBM’s San Jose Research
Laboratory.
• SQL: Structured Query Language – SQL is a special-purpose programming
language designed for managing data held in a relational database management
system.
• DDL: Data Definition Language – A data definition language or data description
language is a syntax similar to a computer programming language for defining
database schemas.
• DML: Data Manipulation Language – is similar to a computer programming language
used for selecting, inserting, deleting and updating data in a database.
• OLAP: Online Analytical Processing – is an approach to answering multi-
dimensional analytical queries quickly.
• OLTP: Online Transactional Processing – a class of IT applications that facilitates
transaction-oriented systems, usually for data entry and retrieval transaction
processing.
• CRUD: Create Read Update Delete – Perhaps the most common acronym of them
all which stands for Create, Read, Update, and Delete.

Kicking the MySQL Tires


You now have a rudimentary grasp of the high level overview of database technology. Now
we can jump in to actually using MySQL from the command line. The first thing we’ll do is
to take a look at the information_schema database. Let’s take a look at the tables in this
database.
mysql> show tables from information_schema;

+---------------------------------------+
| Tables_in_information_schema |
+---------------------------------------+
| CHARACTER_SETS |
| COLLATIONS |
| COLLATION_CHARACTER_SET_APPLICABILITY |
| COLUMNS |
| COLUMN_PRIVILEGES |
| ENGINES |
| EVENTS |
| FILES |
| GLOBAL_STATUS |
| GLOBAL_VARIABLES |
| KEY_COLUMN_USAGE |
| OPTIMIZER_TRACE |
| PARAMETERS |
| PARTITIONS |
| PLUGINS |
| PROCESSLIST |
| PROFILING |
| REFERENTIAL_CONSTRAINTS |
| ROUTINES |
| SCHEMATA |
| SCHEMA_PRIVILEGES |
| SESSION_STATUS |
| SESSION_VARIABLES |
| STATISTICS |
| TABLES |
| TABLESPACES |
| TABLE_CONSTRAINTS |
| TABLE_PRIVILEGES |
| TRIGGERS |
| USER_PRIVILEGES |
| VIEWS |
| INNODB_LOCKS |
| INNODB_TRX |
| INNODB_SYS_DATAFILES |
| INNODB_LOCK_WAITS |
| INNODB_SYS_TABLESTATS |
| INNODB_CMP |
| INNODB_METRICS |
| INNODB_CMP_RESET |
| INNODB_CMP_PER_INDEX |
| INNODB_CMPMEM_RESET |
| INNODB_FT_DELETED |
| INNODB_BUFFER_PAGE_LRU |
| INNODB_SYS_FOREIGN |
| INNODB_SYS_COLUMNS |
| INNODB_SYS_INDEXES |
| INNODB_FT_DEFAULT_STOPWORD |
| INNODB_SYS_FIELDS |
| INNODB_CMP_PER_INDEX_RESET |
| INNODB_BUFFER_PAGE |
| INNODB_CMPMEM |
| INNODB_FT_INDEX_TABLE |
| INNODB_FT_BEING_DELETED |
| INNODB_SYS_TABLESPACES |
| INNODB_FT_INDEX_CACHE |
| INNODB_SYS_FOREIGN_COLS |
| INNODB_SYS_TABLES |
| INNODB_BUFFER_POOL_STATS |
| INNODB_FT_CONFIG |
+---------------------------------------+
59 rows in set (0.03 sec)

Very slick! You’ll notice we had to specify what database to view tables from. Let’s fix that
by changing the database to use.
mysql> use information_schema;

Database changed

mysql> show tables;


This will give us the same result, but now we don’t have to specify which database we’re
trying to view tables on. The reason for this is because we switched databases with the
use command.
We can drill down further and view columns on various tables from within the database.
Let’s see how.
mysql> show columns from schemata;

+----------------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------------------+--------------+------+-----+---------+-------+
| CATALOG_NAME | varchar(512) | NO | | | |
| SCHEMA_NAME | varchar(64) | NO | | | |
| DEFAULT_CHARACTER_SET_NAME | varchar(32) | NO | | | |
| DEFAULT_COLLATION_NAME | varchar(32) | NO | | | |
| SQL_PATH | varchar(512) | YES | | NULL | |
+----------------------------+--------------+------+-----+---------+-------+
5 rows in set (0.01 sec)

Using Dot Notation


MySQL also has the ability to use dot notation so that you can view tables that are not part
of the currently in use database. This is how to do this.
mysql> use mysql

Database changed

mysql> show columns from information_schema.schemata;


This will produce the same output as the prior example, but do note that first we changed
the default database from information_schema to mysql. From there we were still able to
get information about information_schema by using the dot notation to reference it.

Getting Help with MySQL


If you’re at the command line and you run into trouble, your first thought might be to hit that
Google Search box. That’s not a bad idea actually. Built in to MySQL however is a great
help system that you have access to. Let’s test it out.
Let’s say you need help with the SHOW command:
mysql> help show;

Name: 'SHOW'
Description:
SHOW has many forms that provide information about databases, tables,
columns, or status information about the server. This section describes
those following:

SHOW AUTHORS
SHOW {BINARY | MASTER} LOGS
SHOW BINLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count
SHOW CHARACTER SET [like_or_where]
SHOW COLLATION [like_or_where]
SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [like_or_where]
SHOW CONTRIBUTORS
SHOW CREATE DATABASE db_name
SHOW CREATE EVENT event_name
SHOW CREATE FUNCTION func_name
SHOW CREATE PROCEDURE proc_name
SHOW CREATE TABLE tbl_name
SHOW CREATE TRIGGER trigger_name
SHOW CREATE VIEW view_name
SHOW DATABASES [like_or_where]
SHOW ENGINE engine_name {STATUS | MUTEX}
SHOW [STORAGE] ENGINES
SHOW ERRORS [LIMIT [offset,] row_count]
SHOW EVENTS
SHOW FUNCTION CODE func_name
SHOW FUNCTION STATUS [like_or_where]
SHOW GRANTS FOR user
SHOW INDEX FROM tbl_name [FROM db_name]
SHOW MASTER STATUS
SHOW OPEN TABLES [FROM db_name] [like_or_where]
SHOW PLUGINS
SHOW PROCEDURE CODE proc_name
SHOW PROCEDURE STATUS [like_or_where]
SHOW PRIVILEGES
SHOW [FULL] PROCESSLIST
SHOW PROFILE [types] [FOR QUERY n] [OFFSET n] [LIMIT n]
SHOW PROFILES
SHOW SLAVE HOSTS
SHOW SLAVE STATUS
SHOW [GLOBAL | SESSION] STATUS [like_or_where]
SHOW TABLE STATUS [FROM db_name] [like_or_where]
SHOW [FULL] TABLES [FROM db_name] [like_or_where]
SHOW TRIGGERS [FROM db_name] [like_or_where]
SHOW [GLOBAL | SESSION] VARIABLES [like_or_where]
SHOW WARNINGS [LIMIT [offset,] row_count]

like_or_where:
LIKE 'pattern'
| WHERE expr

If the syntax for a given SHOW statement includes a LIKE 'pattern'


part, 'pattern' is a string that can contain the SQL "%" and "_"
wildcard characters. The pattern is useful for restricting statement
output to matching values.

Several SHOW statements also accept a WHERE clause that provides more
flexibility in specifying which rows to display. See
http://dev.mysql.com/doc/refman/5.6/en/extended-show.html.

URL: http://dev.mysql.com/doc/refman/5.6/en/show.html
As we can see here, you are greeted with a wealth of great information relating to the
show command. It gives you a nice overview along with detailed examples. Finally, at the
end of this output, they provide a link for you to go right to the point in the official
documentation for more information. Very nice.
MySQL Introduction Conclusion
This has been a great introduction to database technology as well as MySQL.
We’ll be digging in much further as we move through this web series to make
sure our database interaction skill are up to speed. When we’re writing native
PHP or using frameworks to provide a persistence layer to our application, if we
don’t have knowledge of the fundamentals that our application is effecting, we
could run into some hiccups.

Data Types in MySQL


Not all data is created equal! We know from working with variables in PHP and
JavaScript that variables can hold all kinds of data. MySQL is not different in
this sense. The various data types in MySQL will have an impact on how much
space on disk the database will use. They will also have an impact on
performance. If the data types in use for your fields are not optimized, you could
run into a slow running application, with your database being the bottleneck.
Now that we have a good Introduction to MySQL under our belt, let’s take a
closer look at data types in MySQL and wrap our arms around the nuts and
bolts of how they work.

We can start out by taking a look at the schemata table from the information_schema
database.
mysql> show columns from information_schema.schemata;

+----------------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------------------+--------------+------+-----+---------+-------+
| CATALOG_NAME | varchar(512) | NO | | | |
| SCHEMA_NAME | varchar(64) | NO | | | |
| DEFAULT_CHARACTER_SET_NAME | varchar(32) | NO | | | |
| DEFAULT_COLLATION_NAME | varchar(32) | NO | | | |
| SQL_PATH | varchar(512) | YES | | NULL | |
+----------------------------+--------------+------+-----+---------+-------+
5 rows in set (0.01 sec)
What we want to do here is focus on that second column named type. This is what tells us
what data type will be stored here. The results here are all of the varchar data type. In
addition, we can see that each field has a specific number associated with the varchar.
This is telling us how many characters can be stored. Let’s quickly define a few data types.
Varcar
This is a very flexible data type for strings, especially when you are not sure exactly how
long the length will be. Names and addresses are common uses for the varchar data type.
Varchar has a maximum of 255 characters per field.
Char
When you know how many characters you need, you can make use of the char data type.
This is a fixed width data type. Therefore, you don’t want to allocate a char data type with a
56 character size if you are only going to use 3 characters. It is best to use char only when
the data to be stored will have the same length. Accuracy counts here.
Text
The text data type is a character string just like varchar and char. It is a variable length
data type which can go up to four gigabytes per field! Use this data type carefully.

Character Sets and Bytes


This leads us to an interesting paradox. When defining database fields, we get to specify
the length in characters that a field will hold. We are not able to specify the number of
bytes however. This is where character sets come in.
latin1 is the default character set in MySQL and it uses 1 byte of data per character to be
stored in the database. Note: If you end up with data that requires more than the 1 byte
offered by latin1, the data might appear as question marks in the database – not fun!
utf8 on the other hand used up to 4 bytes per character. If you have an application that
might be using foreign languages, or any type of special characters, you might want to
consider changing your character set to utf8.

What are MySQL Text Sizes?


There are four different ways to define a text field. These are TINYTEXT, TEXT,
MEDIUMTEXT, and LONGTEXT. What type you choose depends on how much you want
to store. In general, it is a best practice to use the smallest data type possible to store your
data while still allowing your application to run properly. This is because as capacity goes
up, so does overhead. The MySQL docmentation has a great section dedicated to storage
requirements.

Dates and Times


Dates, times, and timestamps are actually strings in the most generic sense, but they do
have their own data types.
• DATE
represented in the form of YYYY-MM-DD for example 2014-08-25
• TIME
represented in the form of HH:MM:SS for example 07:33:29
• YEAR
represented in the form of YY or YYYY for example 14 or 2014
• TIMESTAMP
This is a very useful data type, although it does have a limited range of 1970-01-01
through 2038-01-19. What makes this data type great however, is it’s ability to
automatically populate on record creation or when it is updated.
• DATETIME
This is similar to the TIMESTAMP data type, however it is *not* dynamic. You must
calculate the value you want to enter and manually insert yourself. That’s a
drawback. The benefit however, is that the range is greater.

MySQL Numbers
There are several ways to store numbers depending on what you would like to store in the
database. Like text data, you want to choose the most appropriate type for the data to be
stored.
DECIMAL
You can store very specific numeric values with the DECIMAL data type. Let’s say you
want to store the cost of a product, and you know that all products are going to be less
than 100. We could specify DECIMAL(4,2). This would instruct MySQL to store four total
digits with 2 digits after the decimal point. This would allow for -99.99 up to 99.99. Note the
four total digits and two digits after the decimal point.
INTEGER
Integers are typically used for a unique id or some similar type of representation. The idea
of integers brings into the concept of unsigned values. Most times, when you’re using
integers, you won’t have a need for negative values. In this case, your integer will be
unsigned.
Another interesting feature of this data type is automatic number assignment. You may be
familiar with the idea of an auto incrementing id. AUTOINCREMENT is usually used in
combination with the UNSIGNED data type. This way, you have an automatically updating,
non negative, integer for use in your tables. This is unique to MySQL, it is not a part of
standard SQL.
ENUM
The ENUM is a fancy looking datatype and may have confused you in the past. Be
confused no more! ENUM simply stands for Enumerated list, and it is perfect for Yes / No
type values to be stored. Instead of storing actual text to represent something in your
application, it stores a number. Behind the scenes however, it is in fact associating that
number to a specific text value. When you query the database, you will see the actual text.
Think of options like free, paid, premium, or admin. With ENUM, you can easily allow for
those 4 options, and do so within a small footprint of memory. Be advised, you can only
choose one possible value. Think of it like a select tag in html.
SET
What if you want to have an array of choices so to speak, yet you would like to have more
than one option selected? This is what the SET data type is for. A SET field can store up to
64 values. You are allowed to store none, some, or all of the available options.
MySQL Data Types Summary
While not the most exciting of things to have to know, data types in MySQL are one of
those bread and butter topics that you just have to be aware of. In this episode, we
covered several data types and what they can be used for. Let’s check out a table here:

MySQL Data Types

Strings VARCHAR, CHAR, TEXT

Date/time DATE, TIME, YEAR, TIMESTAMP, DATETIME

Numbers DECIMAL, INT

Lists ENUM, SET

The Declarative Nature of SQL

We’ve been covering a lot of information about database technology, terms,


and ideas so far. Soon we will be diving in to using data manipulation language
to insert, update, and delete data in various databases we’ll create. Before we
get to that point, we need to take a look at a key aspect of the Structured Query
Language in general. This would be the fact that SQL is a Declarative
Language, which is very much a different animal altogether from a procedural
language. You are most likely much more familiar with procedural approaches
in computing. This is why in this episode, we’ll take a closer look at what it
means to be a Declarative Language, and how we will need to adjust our
thinking to best make use of it.

What is a Declarative Language?


If you’re like most web developers, you probably found things like PHP and JavaScript
more exciting than SQL when you first began. After all, when we think of programming, we
think of actually doing something or taking an action. SQL isn’t really the first thing that
comes to mind when following this type of thinking. The deal here is that those languages
that you probably first cut your teeth on are procedural. This means they follow a step by
step process of how to do something.
SQL on the other hand is a Declarative Language. In a declarative language, the
programmer declares what she wants, and not how to do it. It is a subtle yet profound
paradigm shift of how you might be used to doing things. All in all, SQL is fairly
straightforward, but if you’ve ever found yourself scratching your head at how to approach
solving a problem in SQL, it may be due to this very difference in programming
approaches. It definitely takes a different mindset and process than you might be used to.

Basic SQL Structure


All SQL follows a convention of selecting what you want, where you want it from, and
include any filters to apply. It looks a bit like this:
SELECT … FROM … WHERE
Following this convention, we could write the following query:
SELECT post_name
FROM wp_posts
WHERE post_title LIKE '%laravel%';

This is pretty cool. Basically it breaks down like so. The SELECT is what to get.
The FROM dictates the location to look in, and the WHERE is the condition that will apply.
The LIKE portion uses the MySQL wildcard characters which is just a percent sign, to
search for any data within the posts_table that contains the term ‘laravel’. This outlines the
declarative approach. Notice that query above does not say something like, get all the post
names, loop through each name to see if it contains laravel, then return the matching
results. That would be a procedural approach which is not what we do in MySQL.
Advantages of a Declarative Language
In a declarative language, one benefit is that it is the database itself that figures out the
procedure. All you have to do is tell the database what you want, it will figure out how to
get that result for you. It is the Optimizer which determines which algorithm will most
efficiently get the data that you ask for. This is a very different approach from what you
might be used to in your usual procedural approach to programming. It helps to know up
front that this is how MySQL works, lest you bang your head against the wall trying to
figure out why your procedural approaches are not working in the future when we get into
more detailed queries. You are essentially relinquishing your control to the database,
rather than using your own logic. You need to think of what you want, not how to get it.
Get It? Got It. Good!
Declarative Language Outline

• Efficient to use
• The database chooses the algorithm
• May be harder to debug than procedural
• Paradigm shift for procedural thinkers

Shifts Focus To Database Design


When you’re programming an application, if things are slow, you can take steps to
optimize the procedure to solve the problem. Maybe you can test a recursive solution
against a simple looping solution. Maybe in other cases, you can use a string function as
opposed to a regular expression. There are many ways to fine tune your application if
need be when using a procedural language. Due to the declarative nature of SQL, this is
not possible when dealing with databases. If you find that your database operations are
running slow, more often than not you’ll be looking at modifying the database schema or
table structure rather than changing the query. Again, this is because MySQL is already
choosing the best procedure or algorithm to provide what you asked for so trying to
change what you are asking for will be of no help. Designing databases is not something
you are apt to be doing on a daily basis unless you are a DBA of some sort. If you’re a web
developer that deals with setting up WordPress Installations for clients, you don’t even
think about the design of the database. Perhaps you’re a plugin developer and maybe you
need an extra table or two in the database. Again, not a real design heavy task. The point
is, is that if you want to get better at database design, it is something you’ll have to practice
and test more frequently than you likely are doing now.
Conclusion
In this episode we covered the fact that SQL is a declarative language. It’s a pretty simple
concept, with the main take away being to think in terms of what you want, not how to get
it. This may be new if you’re used to the procedural approach like most of us probably are.
It may seem like a simple thing, but it is worth having an understanding of to provide a
better foundation for learning MySQL as we progress through this series.

Creating Databases and Tables in MySQL


In this MySQL Series, we first have been taking a look at MySQL and SQL in
general from a high level view. With the vocabulary, acronyms, and theory now
out of the way, we can not focus on putting pen to paper so to speak. This is
where the MySQL Rubber hits the road. We’re going to start working with
databases and tables in MySQL, for without them, we’re not going to be able to
store or retrieve much data. Let’s dig in.

Creating a MySQL Database


Creating a database in MySQL is very straightforward. All you have to do is use the create
databasecommand followed by the name you would like to assign to your database. Don’t
forget to terminate you command with a semicolon. Here we’ll create a database.

mysql> create database vegibit;


Query OK, 1 row affected (0.00 sec)

mysql>

There we go, we’ve created a database to work with. If you made any errors, MySQL will
provide an audible beep and associated error messages to the console. Now what
happens if we try to create a database and the name we choose is already in use? Well,
let’s find out.

mysql> create database vegibit;


ERROR 1007 (HY000): Can't create database 'vegibit'; database exists
mysql>
Ok, that didn’t go so well. Have no fear, MySQL provides a syntax for dealing with exactly
this scenario. If you’d rather have MySQL not bark at you for you’re errors on creating a
database, just add the if not exists clause like so.

mysql> create database if not exists vegibit;


Query OK, 1 row affected, 1 warning (0.00 sec)

mysql>

Interesting. Now check it out. If we get a warning as the result of executing a MySQL
command, MySQL does not display the actual warning by default. Notice it just says 1
warning, but not what it is. We can dig deeper on our own by issuing the show
warnings command.

mysql> show warnings;


+-------+------+--------------------------------------------------+
| Level | Code | Message |
+-------+------+--------------------------------------------------+
| Note | 1007 | Can't create database 'vegibit'; database exists |
+-------+------+--------------------------------------------------+
1 row in set (0.00 sec)

mysql>

Character Sets in MySQL


When creating a database you can specify a character set if you choose. A database itself
is just a collection of tables, so if you assign a character set to a database, what that
means is that once any tables get created, they will have that character set. Be advised! If
you change the database character set after there are already many tables present, those
tables will not be affected! Only new tables going forward will get that character set
applied. You can go ahead and modify the character set manually on existing tables if
need be however.
In MySQL the default character set is latin1, however it may make more sense to choose
ut8-f when creating your databases. This will allow for a much more flexible storage option
as you build out your application. To do this at the command line, simply follow these
steps.

mysql> create database vegibit2 default character set utf8;


Query OK, 1 row affected (0.04 sec)
mysql>

Collation in MySQL
Collation encodes the rules that govern the correct use of characters for the character set.
It also defines the sort order to use on the data as well as the case sensitivity. Character
sets usually have a corresponding collation. The MySQL documentation will give you the
full overview, or you can find this valuable information at the command line like so.

mysql> show character set;


+----------+-----------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+----------+-----------------------------+---------------------+--------+
| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |
| dec8 | DEC West European | dec8_swedish_ci | 1 |
| cp850 | DOS West European | cp850_general_ci | 1 |
| hp8 | HP West European | hp8_english_ci | 1 |
| koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 |
| latin1 | cp1252 West European | latin1_swedish_ci | 1 |
| latin2 | ISO 8859-2 Central European | latin2_general_ci | 1 |
| swe7 | 7bit Swedish | swe7_swedish_ci | 1 |
| ascii | US ASCII | ascii_general_ci | 1 |
| ujis | EUC-JP Japanese | ujis_japanese_ci | 3 |
| sjis | Shift-JIS Japanese | sjis_japanese_ci | 2 |
| hebrew | ISO 8859-8 Hebrew | hebrew_general_ci | 1 |
| tis620 | TIS620 Thai | tis620_thai_ci | 1 |
| euckr | EUC-KR Korean | euckr_korean_ci | 2 |
| koi8u | KOI8-U Ukrainian | koi8u_general_ci | 1 |
| gb2312 | GB2312 Simplified Chinese | gb2312_chinese_ci | 2 |
| greek | ISO 8859-7 Greek | greek_general_ci | 1 |
| cp1250 | Windows Central European | cp1250_general_ci | 1 |
| gbk | GBK Simplified Chinese | gbk_chinese_ci | 2 |
| latin5 | ISO 8859-9 Turkish | latin5_turkish_ci | 1 |
| armscii8 | ARMSCII-8 Armenian | armscii8_general_ci | 1 |
| utf8 | UTF-8 Unicode | utf8_general_ci | 3 |
| ucs2 | UCS-2 Unicode | ucs2_general_ci | 2 |
| cp866 | DOS Russian | cp866_general_ci | 1 |
| keybcs2 | DOS Kamenicky Czech-Slovak | keybcs2_general_ci | 1 |
| macce | Mac Central European | macce_general_ci | 1 |
| macroman | Mac West European | macroman_general_ci | 1 |
| cp852 | DOS Central European | cp852_general_ci | 1 |
| latin7 | ISO 8859-13 Baltic | latin7_general_ci | 1 |
| utf8mb4 | UTF-8 Unicode | utf8mb4_general_ci | 4 |
| cp1251 | Windows Cyrillic | cp1251_general_ci | 1 |
| utf16 | UTF-16 Unicode | utf16_general_ci | 4 |
| utf16le | UTF-16LE Unicode | utf16le_general_ci | 4 |
| cp1256 | Windows Arabic | cp1256_general_ci | 1 |
| cp1257 | Windows Baltic | cp1257_general_ci | 1 |
| utf32 | UTF-32 Unicode | utf32_general_ci | 4 |
| binary | Binary pseudo charset | binary | 1 |
| geostd8 | GEOSTD8 Georgian | geostd8_general_ci | 1 |
| cp932 | SJIS for Windows Japanese | cp932_japanese_ci | 2 |
| eucjpms | UJIS for Windows Japanese | eucjpms_japanese_ci | 3 |
+----------+-----------------------------+---------------------+--------+
40 rows in set (0.00 sec)

mysql>

From the output above, we can see that latin1 uses the latin1_swedish_ci collation, and
utf8 uses the utf8_general_ci collation.

Drop a database in MySQL


It is easy to drop a database in MySQL. Maybe a little too easy. Let’s imagine for a
moment that one of the databases we created earlier has now been in used for a year or
two, and it is storing all kinds of super important data about our business. Customer names
and contact information, sales records, leads and prospects, you name it. Now some junior
dev joins the team and is practicing his MySQL syntax and doesn’t realize he is on the
production database, not the QA database. Our soon to be unemployed dev friend enters
this at the command line.

mysql> drop database vegibit2;


Query OK, 0 rows affected (0.07 sec)
mysql>

and just like that, poof, the database and all associated mission critical data is irreversibly
lost. Of course in real life, there would be backups in place and so on, however this
fictional drama about dropping a database drives the point home. MySQL doesn’t ask you
if you are sure or anything like that, it just happily drops the database along with all
associated tables and data within it. Be careful with dropping databases.
If you try to drop a database that doesn’t exist, you’ll get an error. Let’s see.

mysql> drop database vegibit2;


ERROR 1008 (HY000): Can't drop database 'vegibit2'; database doesn't exist
mysql>

We can apply the if exists clause to dropping databases, and get a warning rather than
an error like so.

mysql> drop database if exists vegibit2;


Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql>

Creating Tables in MySQL


We see how easy it is to create and drop databases in MySQL, now we want to create
some tables. One way to look at how to create tables in a database is to reverse engineer
it. How so you say? By using the show create table command. First we’ll complete some
steps in our terminal, and then review what we just did.

mysql> use laravelblog;


Database changed
mysql> show tables;
+-----------------------+
| Tables_in_laravelblog |
+-----------------------+
| blogpost_tag |
| blogposts |
| migrations |
| tags |
+-----------------------+
4 rows in set (0.00 sec)

mysql> describe migrations;


+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| migration | varchar(255) | NO | | NULL | |
| batch | int(11) | NO | | NULL | |
+-----------+--------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> show create table migrationsG


*************************** 1. row ***************************
Table: migrations
Create Table: CREATE TABLE migrations (
migration varchar(255) COLLATE utf8_unicode_ci NOT NULL,
batch int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
1 row in set (0.00 sec)

mysql>

Ok, so what just happened? Well, first we changed the database we were currently using
to laravelblog by using the use command. Thanks to a prior tutorial, we already have this
database to work with. Ok, once we changed databases, we need to see the tables
contained in that database. Easy enough, we’ll just use show tables to do so. Now we see
which tables we have. Let’s consider that maybe we want to be able to create a table just
like migrations in a different database. How can we do that? Well first we’ll describe it,
and then we’ll apply show create table to it. This gives us the actual syntax we need to
create the table if we want to. Let’s change databases and create this table then!

mysql> use vegibit


Database changed

mysql> create table migrations (


-> migration varchar(255) collate utf8_unicode_ci not null,
-> batch int(11) not null
-> ) engine=innodb default charset=utf8 collate=utf8_unicode_ci;
Query OK, 0 rows affected (0.19 sec)

mysql> describe migrations;


+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| migration | varchar(255) | NO | | NULL | |
| batch | int(11) | NO | | NULL | |
+-----------+--------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql>

By describing and reverse engineering our table, we were able to recreate that
Excellent!
table in an entirely different database.
It is worth noting that table creation usually has 3 parts.

• 1. The first part is the table name, this is what comes directly after the create
table command.
• 2. The second part is the column and index definition. These are the fields of the
table. As if this stuff is not confusing enough, somehow it was decided that you can
refer to these things as either columns or fields. Just know they mean the same
thing. This section goes in between parentheses ( ) and multiple column definitions
are separated by commas.
• 3. The third part contains table level options such as the storage engine type,
charset, and comments.

data type definitions


So we can see that the varchar in our table creation code has a numeric value associated
with it of 255. For text based fields, we would expect this. The number signifies this field
can hold a string with a maximum length of 255 characters. Why then do we see a number
associated with an integer data type? Good question. What this signifies is the minimum
display width of the field. So if an INT data type field has an 11 associated with it, data
retrieved will always have at least 11 digits. So what if you store the number 51501 in the
field. What will be returned is 11 digits, left padded with 6 space characters. For example ‘
51501’. In between the tics here is 11 character spaces, with padding on the left. For
integers, you do not have to specify the number, but it will show up in any create table
statements you use. Also note that depending on the application that is interacting with the
MySQL database, you may or may not see the padding on the left. A key point to
remember is that the range of the data type and the size of the storage are not changed
from their usual values no matter what the minimum display width is set to.
per column options
After the declaration of the data type for a given field in the table comes the column
options such as whether it is null, not null, auto increment, or any other default attributes.
Primary and Unique key definitions come in section 2 in between the ( ) once all fields
have been defined with their respective data types and column options. The primary key is
an important one to remember as this is how MySQL stores rows in the database. Note
that every single value in a primary key field must be unique, meaning no to rows within
that field can have the same value.
optional statements
At the very end of the create table statement after the closing parenthesis is where you
can specify various optional values for the table. This includes things like the storage
engine to use, the charset, collation, and any comments you would like to have associated
with the table.

Create Database and Table Practice


The information up to here has been to get us up to speed with what we need to create
databases and tables in MySQL. Let’s now create a more real world scenario. Here we’ll
pretend we would like to create a table that would hold information about our friends. So
first we think about what it is we would like to store in the table. We probably want to store
things like our friends first and last names, their cell phone number, and maybe their
birthday. Let’s see how we can do it.

mysql> create table friends (


-> first_name varchar(40) not null default '',
-> last_name varchar(40) not null default '',
-> cell_phone varchar(20) not null default '',
-> birthday date default null,
-> primary key (first_name, last_name, birthday)
-> );
Query OK, 0 rows affected (0.03 sec)

Great! That seemed to work pretty well. Note that when using the command line we can
simply end each field definition with a comma, then hit enter to bring us to the next line for
the next field definition. Once you are finished, just add the closing parenthesis along with
a closing semi colon, then hit enter. This will tell MySQL that you are finished with your
declaration and to execute the commands you have entered.
Conclusion
Nice work friends. We’re making a lot of progress in this MySQL series and hitting all the
stops, soup to nuts. Some of this very well may be a lot of review for many of you. For
others, some of these concepts may be the first time you’ve seen them. Either way, its
good to revisit the basics since foundation level knowledge is key to our development.

Getting Started with Data Manipulation


Language in MySQL

So far we’ve been hitting what is arguably the more mundane aspects of
dealing with Database Administration. This would be the DDL or data definition
language portion of working with MySQL. It is by using DDL that we are able to
build and modify your databases and tables. Of course this is needed stuff, we
need a database and some tables before we can start inserting, reading,
updating, and deleting some information. Once we do have our database and
tables in place however, we are ready to start applying some DML or data
manipulation language commands to work with the actual data. Let’s get
cooking!

Inserting Data using INSERT


Until now, we’ve not made note of the fact that commands in MySQL are usually all
uppercase. I can’t stand using the shift key, or the caps lock key, so guess what? That’s
right, when I work with MySQL it is in ALL LOWERCASE BABY :-). Ok, small tangent
aside, we’re going to start by looking at the insertcommand, as it is with this command
that we can begin putting information into our database. The basic syntax usually follows
this format:
insert into table (column1, column2, column3…) values (value1, value2, value3…)
You can also use the insert command following this format:
insert into table set column1=’value1′, column2=’value2′, column3=’value3
Let’s revisit the friends table we had already created earlier.

mysql> show create table friendsG


*************************** 1. row ***************************
Table: friends
Create Table: CREATE TABLE friends (
first_name varchar(40) NOT NULL DEFAULT '',
last_name varchar(40) NOT NULL DEFAULT '',
cell_phone varchar(20) NOT NULL DEFAULT '',
birthday date NOT NULL DEFAULT '0000-00-00',
PRIMARY KEY (first_name,last_name,birthday)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

mysql>

Now we can use the insert command to put some friends into our friends table.

mysql> insert into friends (cell_phone, first_name, birthday, last_name) value


s
-> ('423-1423', 'Jim', '1985-07-24', 'Jones');
Query OK, 1 row affected (0.02 sec)

mysql>

Ok, do you notice anything a little strange here? That’s right, we are not required to
provide the columns in the same order with which they were created. MySQL is very
flexible in this sense and as long as you have a one to one mapping between the columns
and values in your insert statement, it will just work. Lets add another imaginary friend
using the alternative syntax.

mysql> insert into friends set first_name='Emmet', last_name='Brickowski', bir


thday='2013-07-15',
-> cell_phone='987-1244';
Query OK, 1 row affected (0.02 sec)
mysql> select * from friends;
+------------+------------+------------+------------+
| first_name | last_name | cell_phone | birthday |
+------------+------------+------------+------------+
| Emmet | Brickowski | 987-1244 | 2013-07-15 |
| Jim | Jones | 423-1423 | 1985-07-24 |
+------------+------------+------------+------------+
2 rows in set (0.00 sec)

mysql>

mysql>

So happy to see that both Jim Jones and Emmet Brickowski are our friends. Lest
Fantastic!
you are unaware, Emmet is the special, which prophecy has foretold will be the one to stop
President Business and his use of The Kragle on humanity. There are a couple of things to
remember when using insert. When inserting dates into the database, make sure they are
quoted, otherwise the MySQL engine will perform arithmetic on the value you give if in the
YYYY-MM-DD format. The same goes for entering phone numbers. Also notice that the
birthdate field has a default value in the table definition. This means that when we insert a
record, we can actually leave off that field if we like.

Batch Inserts with MySQL


We only have two friends, what a bummer. Let’s add some more to our circle, and we’ll do
it using batch inserts which are great fun.

mysql> insert into friends (first_name, last_name, cell_phone)


-> values
-> ('Rick', 'James', '564-6398'), ('Dave', 'Chappelle', '687-3471');
Query OK, 2 rows affected (0.07 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql>

Notice that we can group multiple collections of values to enter into our fields by enclosing
them within parenthesis. Each group will be separated by a comma as well. So in the
example above, we were able to add both Rick and Dave as our new friends with
one insert statement. Pretty cool.
Inserts using only values
Another neat feature of the insert command in MySQL is that you don’t even have to
specify the fields you want to insert data into if you don’t want to. Just provide the values,
and make sure that the mapping is correct. So for example, our table has the fields in the
order of first_name, last_name, cell_phone, and birthday. If we want to insert only using
values, we better be sure we provide the values in that order, because if we don’t we will
get an error, or worse if the data type matches what can be stored in that field, it will simply
insert that incorrect data and give you no indication that there was a problem. Let’s test
this out now.

mysql> insert into friends values ('Sofia','Vergara','487-4612','1972-07-10');


Query OK, 1 row affected (0.00 sec)

mysql> select * from friends;


+------------+------------+------------+------------+
| first_name | last_name | cell_phone | birthday |
+------------+------------+------------+------------+
| Dave | Chappelle | 687-3471 | 0000-00-00 |
| Emmet | Brickowski | 987-1244 | 2013-07-15 |
| Jim | Jones | 423-1423 | 1985-07-24 |
| Rick | James | 564-6398 | 0000-00-00 |
| Sofia | Vergara | 487-4612 | 1972-07-10 |
+------------+------------+------------+------------+
5 rows in set (0.00 sec)

mysql>

Fantastic! Look at our collection of friends now. I really do like that Sofia.

Using the UPDATE command in MySQL


So we have a database full of friends, yet there are a few things to consider. Dave and
Rick never provided their birthday, so we’ll need to fix that. Well, their data is already in the
database, so what do we do? We update their information using the update command.
Here is how to do it for Rick, we’ll do it for Dave as well.
mysql> update friends set birthday='1948-02-01' where first_name='Rick';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0

As we can see the typical update command follows the format of:
update table set column1=value1, column2=value2 where
The update command is very powerful. You have the possibility of changing hundreds or
even thousands of rows that maybe you didn’t intend to. As an example if you did
something like the following query,

mysql> update friends cell_phone='555-5555';

it would update the cell_phone field, but it would update ALL of the cell_phone fields. Now
every single one of your friends has the same cell phone number, and we know this is not
the case. This is a silly example, however updating something of more importance is no
laughing matter. In addition, there is no undo command, so once you make your mistake,
you are stuck with it. If you are unsure, you can do a select statement first, to see how
many rows the query will match. select and update use the same clauses so we can do
this. If we turn the prior statement into a select, it would look like this:

mysql> select cell_phone from friends;


+------------+
| cell_phone |
+------------+
| 687-3471 |
| 987-1244 |
| 423-1423 |
| 564-6398 |
| 487-4612 |
+------------+
5 rows in set (0.00 sec)

mysql>

So by using this technique, we can see that 5 rows are going to be updated had we used
an updateinstead of a select. Maybe we only wanted to update Dave’s cell phone number.
In that case, we can first do a select to determine how we will then write the update. Let’s
check this out.

mysql> select cell_phone from friends where first_name='Dave';


+------------+
| cell_phone |
+------------+
| 687-3471 |
+------------+
1 row in set (0.06 sec)

mysql> update friends set cell_phone='977-5555' where first_name='Dave';


Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select cell_phone from friends where first_name='Dave';


+------------+
| cell_phone |
+------------+
| 977-5555 |
+------------+
1 row in set (0.00 sec)

mysql>

In the example above, we now can see that only the one row was update which is what we
wanted. By first writing the select statement, it helped us figure out how to put together
our update statement to get the result we want. Perfect.

Using DELETE in MySQL


Ahh yes, the good old fashioned delete command. Just in case you thought you couldn’t
do enough damage with the update command, we give you the equally powerful and
dangerous deletecommand. Yes, you should practice using this command in a sandbox
type environment before you take it to your production setup. Most times, you’re going to
want to make sure that a where clause is included in your delete statement. This way you
can narrow down the operation to only a limited amount of data. In the generic sense, it
would look like this format:
delete from table where expression
With the delete command, you do not specify any columns or fields. That is because
with delete, you are deleting whole rows at a time. If your goal was to simply clear out one
value within a row, you could use an update statement instead. Let’s remove a record from
the database now to see how it works.

mysql> delete from friends where last_name='James';


Query OK, 1 row affected (0.04 sec)

mysql> select * from friends;


+------------+------------+------------+------------+
| first_name | last_name | cell_phone | birthday |
+------------+------------+------------+------------+
| Dave | Chappelle | 977-5555 | 1973-08-24 |
| Emmet | Brickowski | 987-1244 | 2013-07-15 |
| Jim | Jones | 423-1423 | 1985-07-24 |
| Sofia | Vergara | 487-4612 | 1972-07-10 |
+------------+------------+------------+------------+
4 rows in set (0.00 sec)

mysql>

Much like we can convert an update statement into a select statement so that we can
safely see what will be affected in the database, we can do the same with
the delete statement so that we don’t go deleting all kinds of rows we did not intend to.
Since the delete statement affects all fields, we can simply translate that to an asterisk
when constructing the corresponding select statement. For example:

mysql> select * from friends where last_name='Jones';


+------------+-----------+------------+------------+
| first_name | last_name | cell_phone | birthday |
+------------+-----------+------------+------------+
| Jim | Jones | 423-1423 | 1985-07-24 |
+------------+-----------+------------+------------+
1 row in set (0.00 sec)

Using a where clause is a good idea in this case. One other thing to know is that if you try
to delete a row that is already gone from the database, that is perfectly fine. MySQL will
simply give you a query ok, with 0 rows affected.
What if you want to delete all rows from a table, how can we do that? Well, it turns out
there are a couple of ways to do this. One of them doesn’t even use the delete command,
however it is a great way to go about completing this task. If we wanted to get rid of all our
friends, we could do either of the following:

delete from friends;

or

truncate table friends;

It turns out the truncate method is the preferred method. When would you do this?
Consider if you had a table in your database that continually tracks some type of history,
which builds up over time, yet has largely inconsequential data. Every so often, it may
make sense to clear out that table to reduce load on the server. That is an ideal application
for the truncate command.

SELECT in MySQL
We saved the best for last, the select command. Retrieving data from a database is
arguably the most important and powerful aspect of working with databases. We’ve been
using select all along during our examples. If you’ve been using MySQL at all,
the select command really just becomes second nature to you since you use it so much.
The really basic format of the select command is just like this:
select from table where expression
There are many more options you can find in the official docs, so be sure to check those
out once your MySQL skills advance. You’ll find yourself visiting those docs frequently, in
addition to copious amounts of Google Searches, and frequent visits to Stack Overflow.
The best way to get up to speed with select is to simply start hammering out some
commands at your console. We can select individual columns, a combination of columns,
or all columns. Here are some example commands and their output:

mysql> select first_name from friends;


+------------+
| first_name |
+------------+
| Dave |
| Emmet |
| Jim |
| Sofia |
+------------+
4 rows in set (0.00 sec)

mysql> select last_name from friends;


+------------+
| last_name |
+------------+
| Chappelle |
| Brickowski |
| Jones |
| Vergara |
+------------+
4 rows in set (0.00 sec)

mysql> select cell_phone from friends;


+------------+
| cell_phone |
+------------+
| 977-5555 |
| 987-1244 |
| 423-1423 |
| 487-4612 |
+------------+
4 rows in set (0.00 sec)

mysql> select cell_phone, last_name from friends;


+------------+------------+
| cell_phone | last_name |
+------------+------------+
| 977-5555 | Chappelle |
| 987-1244 | Brickowski |
| 423-1423 | Jones |
| 487-4612 | Vergara |
+------------+------------+
4 rows in set (0.00 sec)

mysql> select * from friends;


+------------+------------+------------+------------+
| first_name | last_name | cell_phone | birthday |
+------------+------------+------------+------------+
| Dave | Chappelle | 977-5555 | 1973-08-24 |
| Emmet | Brickowski | 987-1244 | 2013-07-15 |
| Jim | Jones | 423-1423 | 1985-07-24 |
| Sofia | Vergara | 487-4612 | 1972-07-10 |
+------------+------------+------------+------------+
4 rows in set (0.00 sec)

As you get better and better at the overall syntax, you can start adding in more clauses
and conditions. There might be a need for distinct data, table joins, group by commands,
order by statements, limits, sort orders, and so on. Their implementation becomes clear
once you find a use case for them.

The DML Conclusion


Data Manipulation Language really is the bread and butter of your data driven applications.
It is by using DML that we can collect and control all kinds of data using our MySQL
database. At the end of the day, it really boils down to only four
commands, insert, select, update, and delete. These commands of course are used in
combination with all kinds of clauses to refine how they operate on the data. Even though
there are many graphical user interface tools available to work with MySQL, practicing
these queries by hand at the console really is the best way to make this stuff stick. This
makes using those graphical tools much more intuitive. It certainly is easier to go from
using the console to a graphical tool than it is to just barely get by using the graphical
application, then have to make things work at the standard MySQL console.

MySQL Function Tutorial


It’s been a great MySQL tutorial series so far and now we’re going to dig even
further into the language. The introduction to MySQL, data types, declarative
nature, and using data manipulation language is a great foundation to start
practicing some queries that are just slightly more advanced. Don’t worry, we’re
taking baby steps here but there are a bunch of concepts that we need to get
our feet wet with. In this episode we’ll be taking a closer look at things like
common functions, math operations, dates and times, and lots more. Let’s jump
right into the action.

Common MySQL Functions


There are many functions built into MySQL that you will find very helpful in your day to day
MySQL adventures. First off though, let’s have a look at the two tables we’ve been working
with so far in this MySQL series. We’ve take the liberty to add more data to our tables
since the last episode, see if you can update your tables using only the MySQL command
line as practice using the DML commands we’ve cov