Sunday, 8 April 2012

PHP - Variables

PHP - Variables

If you have never had any programming, Algebra, or scripting experience, then the concept of variables might be a new concept to you. A detailed explanation of variables is beyond the scope of this tutorial, but we've included a refresher crash course to guide you.


A variable is a means of storing a value, such as text string "Hello World!" or the integer value 4. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again. In PHP you define a variable with the following form:
  • $variable_name = Value;
If you forget that dollar sign at the beginning, it will not work. This is a common mistake for new PHP programmers!
Note: Also, variable names are case-sensitive, so use the exact same capitalization when using a variable. The variables $a_number and $A_number are different variables in PHP's eyes.

A Quick Variable Example

Say that we wanted to store the values that we talked about in the above paragraph. How would we go about doing this? We would first want to make a variable name and then set that equal to the value we want. See our example below for the correct way to do this.

PHP Code:

<?php
$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
?>
Note for programmers: PHP does not require variables to be declared before being initialized.

PHP Variable Naming Conventions

There are a few rules that you need to follow when choosing a name for your PHP variables.
  • PHP variables must start with a letter or underscore "_".
  • PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
  • Variables with more than one word should be separated with underscores. $my_variable
  • Variables with more than one word can also be distinguished with capitalization. $myVariable

Wednesday, 21 March 2012

Javascript - getElementById

JavaScript getElementById

Have you ever tried to use JavaScript to do some form validation? Did you have any trouble using JavaScript to grab the value of your text field? There's an easy way to access any HTML element, and it's through the use of id attributes and the getElementById function.

JavaScript document.getElementById

If you want to quickly access the value of an HTML input give it an id to make your life a lot easier. This small script below will check to see if there is any text in the text field "myText". The argument that getElementById requires is the id of the HTML element you wish to utilize.

JavaScript Code:

<script type="text/javascript">
function notEmpty(){
 var myTextField = document.getElementById('myText');
 if(myTextField.value != "")
  alert("You entered: " + myTextField.value)
 else
  alert("Would you please enter some text?")  
}
</script>
<input type='text' id='myText' />
<input type='button' onclick='notEmpty()' value='Form Checker' />

Display:

document.getElementById returned a reference to our HTML element myText. We stored this reference into a variable, myTextField, and then used the value property that all input elements have to use to grab the value the user enters.
There are other ways to accomplish what the above script does, but this is definitely a straight-forward and browser-compatible approach.

Things to Remember About getElementById

When using the getElementById function, you need to remember a few things to ensure that everything goes smoothly. You always need to remember that getElementById is a method (or function) of the document object. This means you can only access it by using document.getElementById.
Also, be sure that you set your HTML elements' id attributes if you want to be able to use this function. Without an id, you'll be dead in the water.
If you want to access the text within a non-input HTML element, then you are going to have to use the innerHTML property instead of value. The next lesson goes into more detail about the uses of innerHTML.

Javascript - Compare

JavaScript String Compare

Comparing strings in JavaScript is quite easy, as long as you know about the equals operator and the JavaScript If Statement. This is all you need to know to find out if two strings of your choosing are equal.

Comparing one String to another String

Below we have created a fake authentication system and use an if statement to see if the user's name will grant them access to a special message.

JavaScript Code:

<script type="text/javascript">
var username = "Agent006";
if(username == "Agent007")
 document.write("Welcome special agent 007"); 
else
 document.write("Access Denied!"); 
document.write("<br /><br />Would you like to try again?<br /><br />");

// User enters a different name
username = "Agent007";
if(username == "Agent007")
 document.write("Welcome special agent 007"); 
else
 document.write("Access Denied!"); 

</script>

Display:

Access Denied!

Would you like to try again?

Welcome special agent 007
Be sure you realize that when you are comparing one string to another, you use two equals operators "==" instead of just one "=". When you use two equals operators, it means you are comparing two values.
In this case, the English translation of our program would be: "If username is equal to Agent007, then print out a welcome message; otherwise, access is denied."

Case Insensitive String Compare

Above, we used a case sensitive compare, meaning that if the capitalization wasn't exactly the same in both strings, the if statement would fail. If you would like to just check that a certain word is entered, without worrying about the capitalization, use the toLowerCase function.

JavaScript Code:

<script type="text/javascript">
var username = "someAgent";
if(username == "SomeAgent")
 document.write("Welcome special agent"); 
else
 document.write("Access Denied!"); 
 
// Now as case insensitive
document.write("<br /><br />Let's try it with toLowerCase<br /><br />");
if(username.toLowerCase() == "SomeAgent".toLowerCase())
 document.write("Welcome special agent"); 
else
 document.write("Access Denied!"); 
</script>

Display:

Access Denied!

Let's try it with toLowerCase

Welcome special agent
By converting both strings to lowercase, we were able to remove the problem of it failing to find a match when the capitalization was slightly off. In this case, the "s" was capitalized in the username, but not capitalized in our if statement check.

Javascript - indexOf

JavaScript String indexOf

Ever want to find something in one of your JavaScript strings? Maybe even start your search halfway through the string? Well you're in luck! The string function indexOf lets you supply one required argument (the search query) and one optional argument (the offset) for all your simple searching needs.

If you are looking for a more powerful search feature, you should check out JavaScript's string search function, which has support for regular expressions, but not offsets.

String indexOf Function

As we mentioned above, indexOf has two arguments, with the second one being optional:
  1. SearchString - What you would like to search for.
  2. Offset (optional) - How far into the string you would like the search to begin. If you want to search the whole string, omit this argument.

indexOf Function Example

To start off with, we will be finding the position of the "www" in a typical URL string. The indexOf function will return the location of the first match that it encounters.

JavaScript Code:

<script type="text/javascript">
var aURL = "http://www.xacode.tk/";
var aPosition = aURL.indexOf("www");

document.write("The position of www  =  " + aPosition); 
</script>

Display:

The position of www = 7
If you'd like to follow along with how this function does it's counting, here's a complete breakdown:
  • h - 0 - no match
  • t - 1 - no match
  • t - 2 - no match
  • p - 3 - no match
  • : - 4 - no match
  • / - 5 - no match
  • / - 6 - no match
  • w - 7 - maybe match
  • w - 8 - maybe match
  • w - 9 - It's a match, return the position of the start of the match (7).
Let's see what happens when we add another www to the URL string to see if this function gets confused or not.

JavaScript Code:

<script type="text/javascript">
var aURL = "http://www.xacode.tk/www.html";
var aPosition = aURL.indexOf("www");

document.write("The position of www  =  " + aPosition); 

</script>

Display:

The position of www = 7
Looks like it returned the position of the first "www", just as we expected, so there are no surprises in this function. However, what would we do if we wanted to find the second "www"? Well, we'd have to use an offset, for starters.

indexOf Function Offset Example

If we use the indexOf function to find the first "www", then we can use that position + 1 as a way to skip the first "www" and find the second.

JavaScript Code:

<script type="text/javascript">
var aURL = "http://www.xacode.tk/www.html";
var aPosition = aURL.indexOf("www");
var secondPos = aURL.indexOf("www", aPosition + 1);

document.write("The position of www  =  " + aPosition); 
document.write("<br />The position of the second www  =  " + secondPos); 

</script>

Display:

The position of www = 7
The position of the second www = 21
By using an offset of 8 (7 + 1), we were able to skip the first "www" to instead find the second. In case you're interested in what the function was actually looking at after we gave an offset, we have it below:
  • ww.xacode.tk/www.html
There are only 2 w's left at the beginning of the string, due to the offset, making it impossible for a match to be found at the first set of "www".

Javascript - Replace

JavaScript String Replace

JavaScript's String Object has a handy function that lets you replace words that occur within the string. This comes in handy if you have a form letter with a default reference of "username". With the replace function you could grab get the person's name with an HTML form or JavaScript prompt and then replace all occurrences of "username" with the value that they entered.

String Replace Function

The string replace function has two arguments:
  1. SearchFor - What word is going to be replaced. This can be a string or a regular expression.
  2. ReplaceText - What the word will be replaced with. This needs to be a string.
replace returns the new string with the replaces, but if there weren't any words to replace, then the original string is returned.

Replace Function: String Replace

To start off with, let's just search for a string and replace it with the visitor's name. The first argument is what we are searching for, and the second argument is what we are going to replace.

JavaScript Code:

<script type="text/javascript">
var visitorName = "Chuck";
var myOldString = "Hello username! I hope you enjoy your stay username.";
var myNewString = myOldString.replace("username", visitorName);

document.write("Old string =  " + myOldString); 
document.write("<br />New string = " + myNewString);

</script>

Display:

Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay username.
Notice that only the first occurrence of "username" was replaced. This is the drawback to using a string as your searchFor argument. But don't worry you can replace all occurrences of "username" if you decide to use regular expressions.

Replace Function: Regular Expression

Let's do the exact same replace, except this time, we'll use a a regular expression instead of a string. The only change we need to make is to surround our searchFor word with slashes / / instead of quotations " ".

JavaScript Code:

<script type="text/javascript">
var visitorName = "Chuck";
var myOldString = "Hello username! I hope you enjoy your stay username.";
var myNewString = myOldString.replace(/username/, visitorName);

document.write("Old string =  " + myOldString); 
document.write("<br />New string = " + myNewString);

</script>

Display:

Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay username.
Darn! No luck. We've still only replaced the first "username" with Chuck instead of all of them. What's the solution to our problem? The answer is enabling the global property for our regular expression.

Replace Function: Global Regular Expression

By enabling the global property of our regular expression, we can go from replacing one match at a time to replacing all matches at once. To enable the global property, just put a "g" at the end of the regular expression.

JavaScript Code:

<script type="text/javascript">
var visitorName = "Chuck";
var myOldString = "Hello username! I hope you enjoy your stay username.";
var myNewString = myOldString.replace(/username/g, visitorName);

document.write("Old string =  " + myOldString); 
document.write("<br />New string = " + myNewString);

</script>

Display:

Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay Chuck.
Finally we've succeeded! Remember that if you just want to replace one word, you should use a string or normal regular expression as your searchFor parameter. However, if you want to replace everything, be sure to write a regular expression and append a little g at the end!

Javascript - Search

JavaScript String Search

Knowing if something is or isn't in a string can be very important. If you have an online forum and don't want people to be able to create usernames that include swear words, you can use the search function to find bad words in usernames and reject them if any were found.

String Search Function

This string function takes a regular expression and then examines that string to see if there are any matches for that expression. If there is a match , it will return the position in the string where the match was found. If there isn't a match, it will return -1. We won't be going into great depth about regular expressions, but we will show you how to search for words in a string.

Search Function Regular Expression

The most important thing to remember when creating a regular expression is that it must be surrounded with slashes /regular expression/. With that knowledge let's search a string to see if a common name "Alex" is inside it.

JavaScript Code:

<script type="text/javascript">
var myRegExp = /Alex/;
var string1 = "Today John went to the store and talked with Alex.";
var matchPos1 = string1.search(myRegExp);

if(matchPos1 != -1)
 document.write("There was a match at position " + matchPos1); 
else
 document.write("There was no match in the first string");

 
</script>

Display:

There was a match at position 45
Notice that our regular expression was just the name "Alex". The search function then used this name to see if "Alex" existed in string1. A match was found, and the position of the match (45), was returned.

String Search Function: Alternative Searches

Another basic tool for regular expressions is the pipe character "|" (it's below the Backspace key on standard keyboards) which allows you to search for alternative words /RegExp1|RegExp2/. Instead of just searching for just one word, we can now use the pipe character to search for multiple words.

JavaScript Code:

<script type="text/javascript">
var myRegExp = /Alex|John/;
var string1 = "Today John went to the store and talked with Alex.";
var matchPos1 = string1.search(myRegExp);

if(matchPos1 != -1)
 document.write("There was a match at position " + matchPos1); 
else
 document.write("There was no match in the first string");

 
</script>

Display:

There was a match at position 6
Notice that our regular expression had two names: Alex and John. The search function then used these names to try to find the first occurrence in the string string1. John came before Alex in our string, so its position (6), was returned.
Let's look at a couple more advanced examples.

Advanced Search Function Examples

The following examples play around with the names a little so you can clearly see how the search function operates.

JavaScript Code:

<script type="text/javascript">
var myRegExp1 = /Tom|Jan|Alex/;
var string1 = "John went to the store and talked with Alexandra today.";
var matchPos1 = string1.search(myRegExp1);

if(matchPos1 != -1)
 document.write("The first string found a match at " + matchPos1);
else
 document.write("No match was found in the first string"); 

var myRegExp2 = /Tom|Jan|Alex /;
var string2 = "John went to the store and talked with Alexandra today.";
var matchPos2 = string2.search(myRegExp2);
if(matchPos2 != -1)
 document.write("<br />The second string found a match at " + matchPos2); 
else
 document.write("<br />No match was found in the second string");
 
var myRegExp3 = /Tom|Jan|Alexandra/;
var string3 = "John went to the store and talked with Alexandra today.";
var matchPos3 = string3.search(myRegExp3);
if(matchPos3 != -1)
 document.write("<br />The third string found a match at " + matchPos3); 
else
 document.write("<br />No match was found in the third string");

var myRegExp4 = /Tom|Jan|Alexandra/;
var string4 = "John went to the store and talked with Alex today.";
var matchPos4 = string4.search(myRegExp4);
if(matchPos4 != -1)
 document.write("<br />The fourth string found a match at " + matchPos4); 
else
 document.write("<br />No match was found in the fourth string");
</script>

Display:

The first string found a match at 39
No match was found in the second string
The third string found a match at 39
No match was found in the fourth string
In the first search, a match was found. This is because our search didn't specify that the name had to be exactly Alex, and because the name Alexandra contains "Alex", a match was found.
In the second search, we fixed this by adding a space after the name Alex to make our search for "Alex ", and no match was found.
In the third search, we changed our expression to include "Alexandra" and found a match.
In the fourth and final search, we changed our string to include "Alex" and we didn't find a match.

Javascript - Split

JavaScript String Split Function

The ability to split up a string into separate chunks has been supported in many programming languages, and it is available in JavaScript as well. If you have a long string like "Bobby Susan Tracy Jack Phil Yannis" and want to store each name separately, you can specify the space character " " and have the split function create a new chunk every time it sees a space.

Split Function: Delimiter

The space character " " we mentioned will be our delimiter and it is used by the split function as a way of breaking up the string. Every time it sees the delimiter we specified, it will create a new element in an array. The first argument of the split function is the delimiter.

Simple Split Function Example

Let's start off with a little example that takes a string of numbers and splits when it sees the number 5. That means the delimiter for this example is 5. Notice that the split function returns an array that we store into mySplitResult.

JavaScript Code:

<script type="text/javascript">
var myString = "123456789";

var mySplitResult = myString.split("5");

document.write("The first element is " + mySplitResult[0]); 
document.write("<br /> The second element is  " + mySplitResult[1]); 
</script>

Display:

The first element is 1234
The second element is 6789
Make sure you realize that because we chose the 5 to be our delimiter, it is not in our result. This is because the delimiter is removed from the string and the remaining characters are separated by the chasm of space that the 5 used to occupy.

Larger Split Function Example

Below we have created a split example to illustrate how this function works with many splits. We have created a string with numbered words zero through four. The delimiter in this example will be the space character " ".

JavaScript Code:

<script type="text/javascript">
var myString = "zero one two three four";

var mySplitResult = myString.split(" ");

for(i = 0; i < mySplitResult.length; i++){
 document.write("<br /> Element " + i + " = " + mySplitResult[i]); 
}
</script>

Display:


Element 0 = zero
Element 1 = one
Element 2 = two
Element 3 = three
Element 4 = four