Watkins Web 3: Blog

Cheat Sheet: PHP Variables and Arrays

First, let’s go over three basic requirements for PHP code to be executed:

  1. Your filenames must end in .php to be interpreted as PHP by the server.
  2. All PHP code must be written inside opening (<?php ) and closing (?>) PHP tags
  3. Your files must be hosted on a server that runs software (usually Apache) that runs PHP files.

Upshot: if your browser is spitting out raw PHP code instead of executing that code, check the three above requirements.

Scalar Variables

In PHP, variables begin with a dollar sign ($) and can be used to store pieces of text (aka strings) as well as numbers. We store information in variables with a PHP statement that begins with the variable name and is followed by the equals sign (aka the “assignment operator”) and the value we wish to store. Note that strings need quotation marks around them, while numbers do not. Variable names cannot contain spaces, hyphens, or most punctuation characters besides the underscore (_). They also may not begin with a number.

<?php
	$my_name = "Joe Schmoe"; // a string needs quotation marks
	$my_age = 23;			// a number doesn't need quotation marks
	echo ("<p>My name is $my_name and my age is $my_age.</p>"); 
?>

When a browser requests our page, PHP will echo the string as HTML (the text in quotes above) but replace the variables with the values that have been stored i them:

<p>My name is Joe Schmoe and my age is 23.</p>

As we’ve explored in class, there are a variety of ways to combine, manipulate, and change variables. Remember that PHP is procedural and in many cases the sequence of your code matters:

<?php
	$my_name = "Joe"; // $my_name is now assigned the value "Joe"
	$my_name = "Fred"; // $my_name is now assigned the value "Fred" -- "Joe" is erased from memory
	$my_name = $my_name . " Shropshire"; // use concatenation operator (.) with a string to assign $my_name the value "Fred Shropshire".
 	$my_age = (5 * 30) - 100; // $my_age is now 50
?>

Arrays

Arrays are also a kind of variable, but they are a bit more complex than scalar variables. If you think of a scalar variable as a text file, arrays are a spreadsheet: they store multiple “elements” in a sequence, and you can access particular elements separately.

Associative Arrays

Suppose you have some information about a user. Rather than store that information in m variables ($user_name, $user_age, $user_nickname), you could use an array to store all that information in the variable $user. Arrays have the following structure: each “element” (an item in the array) has both a key and a value. The key is essentially a name for the element: it identifies which one we’re dealing with, while the value is the contents of that element. For example:

<?php
    // create array elements and assign values
	$user[name] =  "Joseph Schmoe"; // element 1: key is the string "name", value is the string "Joseph Schmoe"
	$user[age] =  25;               // element 2: key is the string "age", value is the number 25
	$user[nickname] =  "Joe";       // element 3: key is the string "nickname", value is the string "Joe"
?>

You access and output the value of each element with the same syntax:

<?php
	echo ("<p>The user is named $user[name], is $user[age] years old, and is nicknamed $user[nickname].</p>"); 
?>

Indexed Arrays

An indexed array is simply an array where the keys are numbers, starting with 0 and incrementing by one whenever an element is added. Indexed arrays are easier to manipulate programmatically (the array keys are fairly predictable), but of course the keys don’t carry much information about what value is stored in each element. They’re most often used for lists of content where the meaning of each element is obvious from the variable name:

<?php
	    // create array elements and assign values
		$site_users[0] =  "jschmoe";
		$site_users[1] =  "bsmith";
		$site_users[2] =  "ajones";
		$site_users[3] =  "cwilson";
?>

If you leave out the keys when assigning the value to an element, PHP will just create numeric keys for you, incrementing them as it goes. So this does exactly the same thing as the code above:

<?php
	    // create array elements and assign values
		$site_users[] =  "jschmoe"; // automatically gets array key 0
		$site_users[] =  "bsmith";  // automatically gets array key 1
		$site_users[] =  "ajones";  // automatically gets array key 2
		$site_users[] =  "cwilson"; // automatically gets array key 3
?>

Using Arrays

We’ve already seen how PHP will replace any variable with its value. What’s tricky about arrays is that you can do this with the keys as well as the whole element:

<?php
		$attribute = "nickname";
		$user = "3";
		echo $user[nickname];      // outputs "Joe";
		echo $user[$attribute];    // also outputs "Joe", because $attribute = "nickname"
	    echo $site_users[3] ;      // outputs "ajones"
	    echo $site_users[$user] ;  // also outputs "ajones", because $user = 3
?>

Cheat Sheet: CSS Positioning

The position property is powerful but can be problematic when used incorrectly. If you’re just trying to create columns for your content or put an image over to one side, you should use CSS floats, not positioning.

But for certain situations, position:absolute, position:relative, and position:fixed are necessary. Here’s a rundown.

position:absolute

Keep in mind that the default state of HTML elements in “normal flow” is position:static;. “Static” is a bit of a deceptive word: it just means that the element naturally takes up space on the page and pushes other elements down (or to the side, if floated) by as much space as it occupies.

When you target an element in CSS and apply position:absolute, a few things happen:

  1. The positioned element is removed from “normal flow”
  2. The positioned element can be moved with the top / bottom and left / right properties, in addition to margins and padding
  3. The other elements on the page no longer “know” the dimensions or location of the positioned element. In fact, they flow down the page as if the element weren’t there at all.

Naturally, this makes position: absolute; useful for making some content overlap other content.

position: relative

Position:relative positions an element “relative” to where it would have been positioned statically. In other words, rather than add a margin-left:20px;, you could use position:relative; left: 20px;.

This is a contrived example, though, and we tend to use position:relative for a totally different purpose: By default, position:absolute’s coordinates are determined by the closest positioned container. This is usually the browser window itself (<body>). Since we often want to use a different container’s coordinates for absolute positioning, we can apply position:relative to the container of our choosing. Without a top or left value, this doesn’t do anything to the container itself. Instead, it allows us to apply position:absolute; to some nested element or elements and have our coordinates be relative to the container.

For example, some HTML:

<div id="main-column">
	<ul id="nav">
		[navigation links]
	</ul>
 </div>

And the CSS:

#main-column {
	width:500px;       /* set a width */
	margin:0 auto;     /* and center it on the page */
	position:relative; /* reset positioning coordinates for elements inside #main-column */
    } 
#nav {
	position:absolute; /* remove from document flow */
	right:20px;        /* this means 20px from the right edge of #main-column */
	top:20px;          /* this means 20px from the top edge of #main-column */
   } 

position:fixed

Like position:absolute;, position:fixed; pulls the content out of normal document flow. In addition, it locks its position (defined by top / bottom and left / right) relative to the browser frame, so the element stays on screen even as the user scrolls.

If you need to apply position:fixed relative to a container, apply position:absolute; to the container first.

Cheat Sheet: CSS Floats

Floats are a useful but tricky tool for altering what we call the “normal flow” of an HTML document. Remember the chief characteristics of normal flow: elements marked up with inline HTML tags (a, strong, em, img) march across the screen as if they were running text, falling to the next line only when they run out of horizontal sapce, whereas block level elements (p, h1, h2, ul, table) start on a new line occupy their own horizontal space.

Float Basics

Sample Image The simplest use case for a float is for an image at the beginning of a paragraph. This paragraph shows the default, unfloated behavior: because images are inline by default, the image takes up space as if it were very large text at the beginning of the paragraph, leaving a large space to the right and above them.

Sample Image In this paragraph I’ve used the same markup, but this time I targeted the image with CSS and applied float:left; as well as a small right margin: the image stays aligned to the left of the page but the paragraph now runs around it nicely.

Notice that this new paragraph also runs around the image. Note: this is the default behavior. Neither of the paragraphs (<p>s) are themselves floated — just the image. Now for some dummy text to finish out the paragraph: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Sample Image Finally, here’s the same image at the beginning of the paragraph again, but with float:right; applied: the image goes as far as it can to the right until it hits the edge of the container, then allows content to flow around it. Now for some dummy text to finish out the paragraph: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Note: I tend to use right margins rather than left margins because I usually want the left edge of the first image (on each row) to align with its container.

Common task: Gallery

Floats come in handy when you want to create a grid of images. Use CSS to target all the images and float them all left, giving each a small right and bottom margin to separate them slightly:

Sample Image Sample Image Sample Image Sample Image Sample Image Sample Image

Common task: Columns with Opposing Floats

Floats can be applied to all sorts of elements besides images: paragraphs, list items, and of course the all-purpose block-level container <div>. When you have a design that requires column-like content areas, the technique known as “Opposing Floats” is often the most reliable. First, mark up your content however you wish and surround each content area with a div. You’ll probably want to give your divs classes or IDs (e.g. <div id="content"> and <div id="sidebar">). Now in CSS, set a width on the columns you will be floating, then float one left and the other right.

This div has been styled with width:20% and float:left;

This div has been styled with width:60% and float:right;. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

The nice part about this technique is that you don’t have to explicitly set a margin to separate the two columns: since the floats are in opposite directions, they naturally leave a space as long as their total width adds up to less than the width of their container. In addition, you don’t need to know in advance which column will end up being taller: the parent container will expand to contain them both.

Clearing Floats

Because of the default way that floats force content to wrap around them (refer to the paragraph above that begins with “notice that this new paragraph…” above), it’s common for a gallery like the one above to mess up the positioning of the heading or paragraph that follows it. Often it appears the content after the floats has been “sucked up” into the floated content.

To fix this problem, there are two possible solutions. The first is to apply clear:both; to the element that you would like to force to begin on a new line. (You could also use clear:left; or clear:right; if you only want to clear one kind and not the other.) This works pretty reliably as long as you can easily target (with CSS) the content that follows the floats in the first place.

Clearfix

However, when content is being inserted dynamically or in different ways on different pages, it’s not always convenient to apply clear:both; — the CSS “hook” just isn’t always available.

So some clever people figured out a way to use a CSS3 selector (:after) to insert some dummy content, clear it, and then hide it from rendering on the page. It’s a hack known as clearfix, and it enables you to clear floats by styling the container of the floats rather than the content that follows it.

The style might look like this in your CSS:

#gallery:after {             /* use :after selector to insert content after the element */
        content: ".";        /* insert a period */
        display: block;      /* set it to be a block-level element */
        height: 0;           /* make sure it doesn't actually add space to the element */
        clear: both;         /* clear the inserted period */
        visibility: hidden;  /* make sure the period doesn't show up in the document */
	}

Using classes

Because clearing floats is such a common task, you may end up filling your CSS file with dozens of statements that clear (or clearfix) this or that element. So many people choose to cheat a bit: in CSS we create classes with the names clear and clearfix and we insert these into our HTML wherever we need to clear some floats.

The CSS looks like this:

/* Float-clearing classes */
.clear   {clear:both;}
.clearfix:after   {content: "."; display: block; height: 0; clear: both; visibility: hidden;}

And in HTML:

[a bunch of stuff involving floats]
<h2 class="clear">The next section</h2>

or

<div class="clearfix">
	[a bunch of stuff involving floats]
 </div>
 <h2>This heading should be fine</h2>

Remember, clear:both; is for ensuring that something that comes after a bunch of floats doesn’t get pulled up into them. You apply it to the element that needs to be cleared. On the other hand, clearfix is intended for the container of floated elements, and ensures the elements that come after that container don’t get pulled up into them.

Project 1 Sketches/Wireframes

Quick reminder: your sketches/wireframes for Project 1 are due Monday, February 6. A good place to start would be sketching the design of the home page, a single post (aka permalink) page, and the complete archive page. And you should have some sample descriptions or images that represent the kind of content you will be posting.

We’ve been doing a lot of code exercises and review over the past few weeks, which will of course be necessary for you to build your site. But right now I’d encourage you to put all that aside and think more generally about structure and visual presentation.

  1. Think critically about the form and content of your blog and the way the two will interrelate. Will your site be an all-purpose notebook to which you add any and all images and text that interest you — a sort of online stream-of consciousness in the manner of Tumblr? Or will it be a more carefully curated and written site, where you publish less frequent but longer posts that guide the reader through a theme with text and images?
  2. What kind of design “moves” will contribute to the goals you have for your site? Should the home page put your reader directly into the full text of a recent post, or does it make more sense to let them choose from the 10 your recent posts? If the latter, should the choice be a visual one (a grid of thumbnail images) or short excerpts from the post text (with “Continue Reading →” links). Is there a role for a icon-drive or color-coding system to help organize your site? What about tagging?
  3. If you are inspired by a website or techinque you’ve seen elsewhere, don’t plan to lift it wholesale for your site. Think about how you might re-invent or change it to suit your needs, and in what ways it will support the “big ideas” behind your project.

Finally, remember that this semester is more about you taking the initiative to explore your own ideas with design and code than it is about completing a pre-defined set of tasks. PHP, HTML, CSS, and Javascript are the tools, not ends in themselves. So above all, choose an interest or set of interests that you will be most enthusiastic about translating into an online project.

Web Hosting

For those of you looking to sign up for your own personal domain and web hosting, take a look at this post from Web 1 for info and recommendations. The only thing I would add is I have heard good things about Webfaction, which has a $9.50/month plan.