A PHP Tutorial for Beginners – Part 5

Luigi Arlotta concludes his series ‘A PHP Tutorial for Beginners’ with a discussion on Arrays. He also discusses topics such as associative arrays. His series has turned out to be an excellent introduction to PHP programming. Especially beginners,who are not even well versed with any kind of programming can begin directly with his tutorial..

Arrays

An Array is a sort of multi-valued variable. It stores one or more values, each one identified by a number representing its position in the array. The exact syntax is shown below

$myArray[5]

We’re referring to the sixth element of the array named myArray. Sixth because array elements always begin with 0. Thus if we use [10], we would be referring to the 11th element of the array.

Similarly to assign the value 5 to the second element of the same array we could use the following

$myArray[1] = 5;

In case you want to have the third value of the array named $myArray stored in a variable named $myVariable we could use

$myVariable = $myArray[2];

Arrays are often used to hold values of related variables. For example there are 100 students and all their ages have to be stored in a program. Instead of using 100 Integer variables, we would use one array (aptly named $ages[100]) which is an array of 100 Integers. This way it would lead to neater and better design on the program. You could then access the 100 elements of such an array using $ages[0] …. $ages[99] .

Array Declaration Methods

The declaration of an array variable can be made by listing the elements that the array would hold right at the time when you declare the array.

$varArray = array (element1, element2, ..., elementN);

$varArray is the name we chose for the array variable, while element1, element2 … elementN are the values stored in the array in position 1, 2… N.

There is a second way to declare an array variable. It is possible to assign a value to each position of the array through the following syntax

$varArray[0] = element1;
$varArray [1] = element2;
.
.
.
$varArray [N-1] = elementN;

Both the above methods perform the same assignment. The first one is more compact, but you need to know the values that you would enter in the array right at the time when you initialize the array. Whereas the second method involves assigning each element of the array one at a time. So you could (if required) compute a particular value in the middle of your program and then assign it any particular array element.

Note: Remember that the first element of an Array is always identified by number zero (0). This means that if an array holds eight elements, they will be numbered from Array[0] to Array[7].

Adding elements to an array

Adding elements to an array (append instruction) can be possible in PHP using the following syntax

$varArray[] = newvalue;

This instruction would append the value ‘ newvalue ‘ to a new element after the existing last element in the array. Suppose the array had 5 values (arrayname[0] ….. arrayname[4]) and you had the above statement, the new value would be assigned to 6th element of that array (arrayname[5]).

Example of using Arrays

Using an Array data type could be useful during data processing operations, too. If we decide to save variables in one array object it would be easier to manage them. This because it is possible to process (read/write/edit) all of them by using a loop structure (for loop or while loop). In fact the loop’s control variable would be used as the array’s index.

Now we are going to define an array and print its content with a for loop. Then we’ll add a new value to the array and finally we’ll print the array again. This is the code for the program

<HTML>
<BODY>
<?

$vv = array ("<BR>","Welcome to ", "Bit After Bit. ", "Loading, just ", 5, " minutes");

for ($k=0;$k<6;$k++)
echo ($vv[$k]);

$vv[]= " or a little more!";

for ($k=0;$k<7;$k++) echo ("$vv[$k]"); ?>
</BODY>
</HTML>

The script above would generate an HTML page which displays the following

Welcome to Bit After Bit. Loading, just 5 minutes
Welcome to Bit After Bit. Loading, just 5 minutes or a little more!

Scalar and Associative Arrays

The array variables we’ve discussed till now are all scalar arrays. Working with scalar arrays, you can access to any elements through an index.

PHP allows to define a second kind of arrays called the associative arrays. An associative array is an array in which the elements can be accessed through a keyword instead of the index. Each element, in an associative array, is characterized by a keyword. This means we’ll no more use indexes to read/write/edit elements, because they have been replaced by keywords. The associative arrays is constituted by pairs such as “key – element”.

The syntax we’ll use to define an associative array is similar to that we have used to define scalar array. We just need to replace indexes with keywords.

$varArray = array (
"key1" => element1;
"key2" => element2;
...
"keyN" => elementN;
);

varArray is the name of the array variable , key1, key2…, keyN are the N keywords through which we can access the respective elements – element1, element2, … elementN.

Look at the following example where associative arrays are used

$website = array(
"name" => "Bit After Bit",
"URL" => "http://www.bitafterbit.com",
"email" => "webmaster@bitafterbit.com",
);

An associative array with three elements has been defined. The first element, accessible through the keyword “name” is of string type and contains the value “Bit After Bit”. The second element is a string too, it is accessible through keyword “URL” and stores the value “http://www.bitafterbit.com”. The third and last element is also a string containing the value “webmaster@bitafterbit.com”.

Once we have defined such an array we could use the following script to display some of the values

Sample Program

<? echo ("Surf to the website $website[name] at $website[URL]!"); ?>

Output of above program

Surf to the website Bit After Bit at http://www.bitafterbit.com

That’s it!! We have covered all the necessary basics that any beginner would like to learn. I hope you’ll have enjoyed this series as much as I have enjoyed writing it..

 

A PHP Tutorial for Beginners-Part 4

A PHP Tutorial for Beginners – Part 4

In this fourth article of this series, Luigi Arlotta explains different datatypes that you can use in PHP. Mainly integers, floats and strings have been dealt with. This article also explains the use of escape characters.

In this entire article, I shall not be providing complete examples, since I assume you know enough of PHP to add the basic tags and other lines required to make a complete program. I shall only be discussing the important part of the programs.

Datatypes

To declare a variable it is sufficient to choose a name, through which the variable will be identified, and then initialize it. It is not necessary, as it happens for other programming languages, to declare the type of the variable. PHP is able to deduce the type of a variable from the value with which it has been initialized. For instance, if we write

$var1 = 7;

PHP will create a variable of integer type with the name ‘ $var1 ‘ and store the value of 7 in it.

If instead we write

$var2 = "This is a variable";

PHP will create a variable of string type named ‘ $var2 ‘ and store the value “This is a variable” in it.

The type of a variable indicates what kind of data the variable will store. The concept of datatypes is particularly important, not only in PHP, but in all programming languages.

A few of the datatypes in PHP are Integers, Floating Point numbers, Strings. I shall explain all of these in the rest of the article.

Datatypes : Integers

Variables of Integer type represent positive and negative integers, or zero. The declaration and initialization of an integer variable has the following syntax

$VarName = IntValue;

$VarName is the name we have chosen for the variable, while IntValue has to be replaced with a datatype compatible number (a positive, negative or zero number).

The various operations that you can perform with integers are shown in the table below.

Arithmetic Operations
$a + $b
Addition
$a – $b
Subtraction
$a * $b
Multiplication
$a / $b
Division
$a % $b
Modulo (Remainder)

 

Increment/Decrement Operators
$a++ OR ++$a
Increment $a by 1
$a– OR –$a
Decrement $a by 1

To make comparisons between integer variables we can use the comparison operators as shown previously while explaining conditional statements. They are summed up for you in the below table.

Comparisons for integer datatypes
$a == $b
$a < $b
$a <= $b
$a >= $b
$a >= $b
$a != $b

Datatypes : floating point numbers

Variables of floating point datatype are used to store numbers with a decimal part. The declaration and initialization of a floating point value has the following syntax

$VarName = FloatValue;

$VarName is the name we have chosen for the variable, while FloatValue has to be replaced with a datatype compatible number.

$x = 3.13;
$y = 0.143;

In order to execute operations with floating point numbers we can use the classic math operators as shown in the table for integer datatypes.

Note: You can carry out all the arithmetic operations with floats that you can perform with integers except the modulo operation. Obviously the module operator (%) lacks, because the division between decimal numbers has no remainder.

You can make similar comparisons between floating point values as you did with integer values.

Datatypes: strings

The declaration of a string variable is same as that of any other variable. The only difference is that the value that you want to store in a string variable must be enclosed in inverted commas or quotes. I have already talked about the existing difference between inverted commas and quotes previously. Here are two string variable declarations. The first one uses inverted commas, while in the second one quotes are used.

$str1 = "This is a string datatype variable";
$str2 = 'This is a string datatype variable, too';

Previously I had said that PHP interprets all that is enclosed between inverted commas and carries out the needed substitutions; whereas it leaves unchanged all that is enclosed between quotes.

Let’s look at some examples that will help us to be familiar with the PHP works. Observe the following script and try to guess the output.

$Civicc = 8;
$Address = "Via Tespi, $Civic";
echo 'My address is $Address';

The script’s output is displayed below

My address is $Address

If you guessed the output right it means you understood this series properly till now. If you have still have some trouble understanding why PHP has printed the variable name instead of its value, the answer once again is : PHP does not interpret the content between quotes.

Here is another script. Try guessing the output.

$Civic = 8;
$Address = "Via Tespi, $Civic";
echo "My address is $Address";

The output of this script is as follows

My address is Via Tespi, 8

By replacing the quotes with the inverted commas in the third line, the PHP interprets the text before printing it. The $Address variable is replaced with its actual value at that instant ( in our program it is equal to Via Tespi, 8).

Note the double substitution that takes place in that line – One for $Address and another for $Civic.

Escape Characters

At this point you may have a doubt. Suppose you want to display something like this in an HTML page using PHP

The value of $Address variable is Via Tespi, 8

As a beginner you may try writing the following 2 scripts if you wanted the above output. but you would be disappointed with the actual output of both these programs

Code for Program 1

$Civic = 8;
$Address = "Via Tespi, $Civic";
echo "The value of $Address variable is $Address";

Output of Program 1

The value of Via Tespi, 8 variable is Via Tespi, 8

 

Code for Program 2

$Civic = 8;
$Address = "Via Tespi, $Civic";
echo 'The value of $Address variable is $Address';
Output of Program 2

The value of $Address variable is $Address

On possible solution to the problem is shown below

$Civic = 8;
$Address = "Via Tespi, $Civic";
echo 'The value of $Address variable';
echo " is $Address";

This above script would display the required output, but we are compromising by using two echo statements rather than one.

An easier and better way exists. It is possible by using escape characters ‘ \ ‘ (backslash) between inverted commas, that allow printing of some special characters.

$Civic = 8;
$Address = "Via Tespi, $Civic";
echo "The value of \$Address variable is $Address";

The above program would display the following output

The value of $Address variable is Via Tespi, 8

Even though we have used inverted commas, addition of the escape character ‘ \ ‘ before the variable name, prevents PHP from interpreting that variable.

Similarly in case you want inverted commas as a part of your output you could use the following

$Civic = 8;
$Address = "Via Tespi, $Civic";
echo "The value of \$Address variable is \"$Address\""

This program would display the following

The value of $Address variable is "Via Tespi, 8"

There are other escape characters as well, that are used to represent special characters. These are shown in the table below.

Escape Characters
\”
Insert an inverted comma in the output
\n
Insert a newline (goes to next line) in the output
\r
Insert a carriage return in the output
\t
Insert a tab in the output
\$
Insert a dollar sign in the output
\\
Insert a backslash in the output

 

A PHP Tutorial for Beginners-Part 3 | A PHP Tutorial for Beginners-Part 5

A PHP Tutorial for Beginners – Part 3

Luigi Arlotta, in his third article continues with his introduction to PHP programming. In this article Luigi explains one more conditional statement called the while loop. He then proceeds and explains one of the most important constructs of any programming language – functions.

while Loops – An Important Conditional Statement

A while loop is a little less sophisticated than a for loop, but it approximately carries out the same function. It is composed of a body containing some instructions and an exit condition. At the beginning of the cycle and each successive iteration, all the instructions in the body are executed, the exit condition consisting of a boolean expression, is checked up. The loop ends when the exit condition returns a false value.

The syntax of a while loop is as follows

while (condition)
{

BodyOfLoop;

}

The condition is the control condition of the loop. The first check of the condition’s validity takes place at the beginning of the cycle, before the first iteration. Also in this case, it can happen that the instructions included in the loop’s body are never executed. This happens when the exit condition immediately returns a false value. As with the for loops, even with the while loops there is the danger to create a never ending loop. This happens when the exit condition never returns a false value.

The example below, prints numbers from 1 to 10 (Just like the example of for loops). I have shown only a part of the program. A more complete and complex example is shown later.

$k = 1;
while($k <=10){

echo("$k <BR>");
$k++;

}

Observe that in this case it is necessary to supply to the increment of the control variable $k, by adding an increase instruction ($k++) in the loop’s body. The output of the program is shown below

1
2
3
4
5
6
7
8
9
10

I have also taken up the example that displays the cell along with the line-cell numbers. This time I have generated the same output using the while loop instead of the for loop.

<HTML>
	<BODY>
	<?
		$j=1;
		echo ("
<TABLE ALIGN=CENTER BORDER=1 CELLSPACING=1 CELLPADDING=5 >");
		while ($j<=5) {
			echo ("
<TR>");
			$k=1;
			while ($k<=3) {
				echo ("
<TD> Line $j, Cell $k </TD>

");
				$k++;
			}
				echo("</TR>

");
				$j++;
		}
		echo ("</TABLE>

");
	?>
	</BODY>
</HTML>

The output of this program is similar to the one using the for loop. The table below is the output.

Line 1, Cell 1
Line 1, Cell 2
Line 1, Cell 3
Line 2, Cell 1
Line 2, Cell 2
Line 2, Cell 3
Line 3, Cell 1
Line 3, Cell 2
Line 3, Cell 3
Line 4, Cell 1
Line 4, Cell 2
Line 4, Cell 3
Line 5, Cell 1
Line 5, Cell 2
Line 5, Cell 3

PHP also provides an alternative syntax for while loops, too. It is possible to avoid the use of the brackets “{” and “}” by enclosing the instructions that constitute the body of the loop with the endwhile keyword. The syntax of a while loop using the endwhile keyword follows

while (condition)

BodyOfLoop;

endwhile;

Just as in the if-then-else statement, we can set up a while loop intermingled with HTML code. The syntax is as follows

<? while (condition) : ?>

HTML instructions

<? endwhile ?>

The table below serves as a quick reference for the syntax of for loops and while loops. Both these return the same result. You could use any of them.

Comparisons of for and while loops
for Loop
while loop
for ($i=0; $i<=10; $i++) {
echo(“Iteration no. $i<BR>”);
}
while ($i<=10) {echo (“Iteration no. $i<BR>”);
$i++;
}

Functions

Functions are blocks of instructions used by the main program in order to achieve its goal. A function generally executes a basic and complete operation. Many such functions together would carry out the main objective of the program.

Every function has a name that identifies it. A function can get as input an arbitrary number of parameters (variables), which can be used within that function. Also if necessary, an output value can be returned to the main program from the function. This value can be saved and used when necessary. Functions are a basic instrument in every programming language. This allows software developers to spilt the application’s main objective into many smaller blocks each concerned with a specific job. This simplifies the application’s building, testing, debugging and editing process. This technique leads to what is called modular programming since the entire program is divided into separate modules (functions).

A function is constituted by a head and a body. In PHP, functions are defined as follows

function FunctionName($param1, $param2, ..., $paramN){

FunctionBody;

}

FunctionName is the name of the function. $param1 , $param2 …, $paramN are the N parameters that the function receives. The parameters sent to a function do not necessarily have to be primitive data types (integers, char, floats, etc.), they can be any type of objects defined by the software developer.

Between the brackets ‘ { ‘ and ‘ } ‘ is the function’s body, containing the instructions to be executed when the function is called. Once these are executed, a value called function’s output can be returned to the program that called this function.

Now we want to define a function that displays some text in a HTML document using a paragraph TAG. This text is passed as parameter. We can write a function like the following one

function writeString ($str)
{

echo("<FONT FACE=\"Comic Sans MS\" SIZE=3>
<P ALIGN=\"JUSTIFY\">$str</P>

</FONT>");

}

To use the writeString() function, we will write the following line inside the PHP code

writeString("Text to be formatted and displayed by the function");

The PHP code of the page in which the writeString() function is used is shown below

<HTML>
	<BODY>
		<?
			function writeString ($str)
			{
				echo("<FONT SIZE=+1>
<P ALIGN=\"JUSTIFY\">$str</P>

</FONT>");
			}

			writeString ("Text to be formatted and displayed by the function");
		
		?>
	</BODY>
</HTML>

The code will generate the following output

Text to be formatted and displayed by the function

The next example is quite a complex example. The PHP script consists of a function that creates a beautiful checkered board using only HTML tags. The number of checkered squares on the board can be passed to the function as input parameters.

<HTML>
	<BODY>
		<?
		function createBoard ($lines, $cols)
		{
			$j=1;
			echo ("
<TABLE ALIGN=CENTER BORDER=1 CELLSPACING=0>");
				while ($j<=$lines) {
					echo ("
<TR>");
					$k=1;
					while ($k<=$cols) { if (($j+$k)%2>0)
							echo ("
<TD WIDTH=30 HEIGHT=30 BGCOLOR=#000000> </TD>

");
						else
							echo ("
<TD WIDTH=30 HEIGHT=30 BGCOLOR=#FFFFFF> </TD>

");
							$k++;
					}
					echo("</TR>

");
					$j++;
				}	
			echo ("</TABLE>

<BR><BR>");
		}

		createBoard(8,8);
		createBoard(4,4);
		?>
	</BODY>
</HTML>

The output of the program shown above would be the following

 

The createBoard(8,8) function call creates the 8×8 checkered board. And the next line createBoard(4,4) creates the smaller 4×4 checkered board. The most important part of the program is the nested for loops (one for loop inside another for loop). The inner for loop would run complete number of times for each iteration of the outer for loop. So if the outer for loop has 10 iterations and the inner for loop has 5 iterations. And suppose there is an echo() statement within the inner for loop, this echo() statement would be called a total of 10×5 times – 50 times.

I hope you liked this article. In my next article I shall explain the different datatypes in PHP. Also I shall deal with strings and explain their usage.

 

A PHP Tutorial for Beginners-Part 2 | A PHP Tutorial for Beginners-Part 4

 

About the Author – Luigi Arlotta arlotta@inwind.it )

A PHP Tutorial for Beginners – Part 2

This is the second article in this series. This time Luigi Arlotta explains in detail, conditional statements such as if-then-else loops, for loops and switch-case structures.

Conditional statements are required in every programming language. These statements execute different parts of the code depending on which condition gets satisfied. I have explained the commonly used conditional statements in this article. We shall begin with the if-then-else statement.

if-then-else Conditional Statement

The if-then-else instruction, through which it is possible to manage the application’s logic flow, has the following syntax in PHP

if (condition)
instruction1;
else
instruction2;

The condition in the above statement is a boolean expression that generally consists of a comparison between a variable and a constant value or a comparison between two variables. A boolean expression returns a true or false value. If a true value is returned, instruction1 is executed, otherwise, if a false value is returned, instruction2 is executed.

Look at the following example code

<HTML>
<BODY>
<? $Lastname = "Bit"; if ($Lastname == "Bit") echo ("Hello, Mr. Bit!"); else echo ("Who are you?"); ?>
</BODY>
</HTML>

It will produce the following output

Hello, Mr. Bit! 

The program checks the following boolean expression (condition) $Lastname == “Bit”, that turns out to be true; so the immediately following echo() statement is executed. The second echo() statement, contained in the else branch, will NOT be executed.

To execute comparisons between variables and/or constant values, you can use the following comparison operators.

Comparison Operator
Description
==
Checks if 1st value is equal to 2nd value
>
Checks if 1st value is greater than 2nd value
<
Checks if 1st value is lesser than 2nd value
!=
Checks if 1st value is not equal to 2nd value
>=
Checks if 1st value is greater than or equal to 2nd value
<=
Checks if 1st value is lesser than or equal to 2nd value

Note that the ‘equal to’ operator (==) is expressed by two symbols “=” (equal) placed side by side (“==”). One of the most common errors is to use a “=” while using a boolean expression (comparing two variables, for instance). This kind of error seriously alters the logic flow of the program. Look at the following 2 statements


if ($Lastname == "Bit") echo "Hello, Mr. Bit!";

if ($Lastname = "Bit") echo "This statement will always be printed";

The first instruction is processed as a comparison operation and it returns a true value if the variable $Lastname stores the value “Bit”, false otherwise. The message “Hello, Mr. Bit!” would only be displayed if the condition turned out to be true.

The second instruction instead assigns the value “Bit” to the variable $Lastname. And this always turns out to be true. Since its just a normal assignment and not a conditional check. Thus the message in case always gets printed.

HTML Intermingled with PHP

PHP provides some alternative ways to write an if-then-else statement. Here is the first one

<? ... if (condition) : ?>
HTML instruction
<? else : ?>
HTML instruction
<? endif ?>

The condition is followed by a first block of HTML instructions that will be executed only if the condition returns a true value. The else keyword is followed by a second HTML block that will be executed if the condition returns a false value. The if-then-else statement finishes with the endif keyword.

The following PHP code is functionally analogous to the first example of this chapter

<HTML>
<BODY>
<? $Surname = "Bit"; if ($Surname == "Bit"): ?>

Hello, Mr. Bit!

<? else: ?>

Who are you?

<? endif ?>
</BODY>
</HTML>

The output will be obviously the same

Hello, Mr. Bit!

If we have more than one instruction to be carried out in a if… then… else… structure, it is necessary to enclose them in the brackets { and } . The brackets task is to create a block where more instructions can be held together. Otherwise we can use the endif keyword as it follows

if (condition)

instruction1;
instruction2;
...
instructionN;
endif;

When we are interested in analyzing more conditions before choosing the instruction to execute, we can create a if… then… else… chain structure. This allows us to specify a set of conditions that will be checked up sequentially. Each condition is checked up only if all the previous ones have returned a false value. When the first true condition is found, all the successive ones will not be processed. The syntax of an if… then… else… chain instruction is the following

if (condition)

instruction1;
elseif
instruction2;
elseif
instruction3;
.
.
.

else
instructionN;

The if-then-else statement can also be used along with boolean logic operators AND, OR and NOT. Such operators are expressed in PHP with special symbols shown in the table below

Logical Operator
Description
&&
Boolean AND
||
Boolean OR
^
Boolean XOR
!
Boolean NOT

The use of these operators allows you to write sophisticated boolean expressions that will be evaluated using something called the truth tables.

In case you are a Math student, you would be knowing all this like the back of your hand. If not I have shown the truth tables for AND, OR and NOT below.

a
b
(a && b)
(a && b)
(!a)
True
True
True
True
False
True
False
False
True
False
False
True
False
True
True
False
False
False
True
True

Enough of truth tables!! Please refer to and book on Math, in case you still haven’t understood truth tables.

Switch Conditional Statement

When it is required to execute a set of comparisons on the same variable, instead of writing an if-else-else instruction, we are used to choose the switch one. Its syntax is as follows

switch ($VarName){

case V1:
Instruction1;
break;

case V2:
Instruction2;
break;

.
.
.
.

case VN:
InstructionN;
break;

default:
Instruction;
break;

}

$VarName is the variable on which comparisons are performed, while V1, V2, V3 are variables or constant values to which $VarName is compared to. When one of the comparison operation returns a true value the corresponding instruction is executed. If no comparison return a true value, the instruction held in the default branch is executed.

Suppose, for instance, that we need to compare the value of an integer variable named $var, with a collection of integer constants. We’ll write

<? $var=2; switch ($var) { case 1: echo ("\$var isn't 1"); break; case 2: echo ("\$var isn't 2"); break; case 5: echo ("\$var isn't 5"); break; default: echo ("\$var value isn't 1, 2 or 5, but $var"); break; } ?>

We could get the same result by writing an if-else-else instruction as it follows

<? $var=2; if ($var==1) echo ("\$var value isn't 1"); elseif ($var==2) echo ("\$var value isn't 2"); elseif ($var==1) echo ("\$var value isn't 3"); else echo("\$var value isn't 1, 2, or 5, but $var"); ?>

Observe that the escape character (” \ “) has been used before the name of the variable. Its purpose is to visualize the ‘$’ character, avoiding that the $var variable is interpreted and replaced with its value. We’ll talk about the escape sequences in later articles.

For Loops – The most used Conditional Statement

Another useful instruction that controls the logic flow of the program, is the for statement. It allows software developers to execute one or more instructions many times, until a particular condition is satisfied. It’s called the condition of escape (or exit condition) for the loop.

The PHP syntax of a for loop instruction is the following one

for ($v=startValue; condition_on_$v; instruction_on_$v){

LoopBody;

}

$v is the control variable of the cycle. $v is initialized to the value startValue when the loop begins. condition_on_$v is the condition of control for the loop. The loop ends when condition_on_$v returns a false value (that’s to say when the condition_on_$v no longer is true). The first check on the condition is carried out before the first iteration; therefore, it is possible that the instructions held in the body of the loop (LoopBody) are never executed. This happens when condition_on_$v immediately returns a false value. instruction_on_$v is an instruction that modifies the value of the control variable $v. With this instruction $v generally moves towards a value that makes condition_on_$v false; in this way the loop execution ends. This should happen after a certain number of iterations. If condition_on_$v never turns out to be false, the risk would be to generate an infinite loop, that to say a never ending loop. All this would be more clear when you read an example.

Here are some examples in which the for loop is used.

The first example simply prints the numbers from one to ten. I have shown you only a part of the complete code. This should be enough to understand. A more complex and complete example is shown later.

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

echo("$k


<TR>");

}

The control variable of the loop is $k. It is first declared and then initialized to the value 1 at the cycle’s beginning. The control condition of the cycle returns a true value until $k is lesser than or equal to 10. The instruction on $k consists of incrementing $k after every iteration. The body of the loop consists of a echo() instruction.

In the first iteration $k has been just initialized to the value 1. The output of the first iteration will be 1. In the second iteration, $k has assumed value 2, therefore the output of the echo() instruction will be 2. The cycle repeats until $k assumes a value of 11. At this step the condition of control ($k <= 10) turns out false and the cycle exits.

The output of the program is

1
2
3
4
5
6
7
8
9
10

The second example uses a for loop to create an HTML Table

<HTML>
<BODY>
<?

echo ("


<TABLE ALIGN=CENTER BORDER=1 CELLSPACING=1 CELLPADDING=5 >");
for ($j=1;$j<=5;$j++) {
echo ("


<TR>");
for ($k=1;$k<=3;$k++)
echo ("


<TD> Line $j, Cell $k </TD>



");
echo("</TR>



");
}
echo ("</TABLE>



");

?>
</BODY>
</HTML>

The above code generates the following output

Line 1, Cell 1
Line 1, Cell 2
Line 1, Cell 3
Line 2, Cell 1
Line 2, Cell 2
Line 2, Cell 3
Line 3, Cell 1
Line 3, Cell 2
Line 3, Cell 3
Line 4, Cell 1
Line 4, Cell 2
Line 4, Cell 3
Line 5, Cell 1
Line 5, Cell 2
Line 5, Cell 3

That’s all for this article. More in the next one..

A PHP Tutorial for Beginners-Part 1 | A PHP Tutorial for Beginners-Part 3

A PHP Tutorial for Beginners – Part 1

PHP is an excellent server-side technology for dynamic webpage generation. Within a span of few years, it has gained immense popularity among developers. This excellent 5-Part tutorial written by Luigi Arlotta explains the basics of PHP programming. His style is so simple that even absolute beginners would have no trouble following this tutorial.

This tutorial is targeted at those users who may have never programmed using any language before. Also programmers who have experience in other languages can quickly browse through this series and get their PHP code running within minutes…

Introduction

PHP stands for “PHP: Hypertext Preprocessor”. PHP is a scripting language through which you can generate web pages dynamically. PHP code is directly inserted in HTML documents through specific TAGs declaring the code presence and then executed when a client demands the page. PHP is a server-side language, that’s to say that PHP code is directly executed by the server, while the client receives processed results as an HTML document. This way of working is different from that of other scripting languages as JavaScript, whose code is first loaded onto the client machine and then executed by the client (the browser).

A few points to note about PHP programming –

1. All compatibility problems existing between different browsers are completely solved. The Client’s browser, receives a normal HTML page after the execution of a PHP code on the server, and so it is always able to display it correctly since it deals with only HTML. This does not happen with scripting languages interpreted by the client’s browser. In this case the client downloads the script code and tries to process it on the local machine. This procedure works correctly only if the client is equipped with the right software (generally called plugins or built-in support in the browser).

2. The server side code processing sees to it that the script code is never visible to the clients. That prevents “thefts” of source code.

3. The server side code execution requires that your webserver has been well configured. It must be able to recognize HTML documents containing PHP code. In order to make this, it is necessary to install a PHP engine and to edit some lines in the webserver’s configuration file.

4. Server side code processing needs resources (CPU time) for generating the dynamic pages. A high number of client requests could overload the server. But generally today’s servers such as Apache are made stable enough to handle a relatively large number of clients.

To make the webserver differentiate between HTML documents containing PHP code and normal HTML pages, .php, .php4 or .phtml extensions are used in place of the .html . These extensions can change according to the webserver configuration. We shall stick to the standard .php extension.

Assume that a client requests the following page (example1.php). The source code for the file is shown below

<HTML>
<BODY>
<?
echo ("
<H1>This is an example</H1>

");
?>
</BODY>
</HTML>

This page will be recognized, thanks to the extension from which it is characterized and it will be processed as a HTML document containing PHP code by the server. The code is interpreted before the output is sent to the client. The webserver passes this page through the PHP engine which processes it and executes the PHP instructions in the code. It then substitutes the result of the execution in place of the original PHP code. Once processed by the PHP engine, the webserver then transmits this dynamically generated page to the client. The client receives the following HTML document

<HTML>
<BODY>

<H1>This is an example</H1>

</BODY>
</HTML>

As you see, in the document sent by the web server to the client there is no sign of PHP code. The code has been interpreted/processed and replaced with HTML lines. The client will never be able to deduce what code generated the particular HTML lines.

PHP instructions are placed inside special TAGs <? and ?>

These tags allow the PHP engine to distinguish the PHP syntax from the rest of the document. It is possible to use different TAGs editing the engine configuration file php.ini . We shall stick to the most common ones – the ones shown above.

Necessary Setup to Run PHP on your machine

To start writing and testing your PHP scripts you need a webserver and a PHP engine. The PHP engine must be combined with the webserver so that the webserver can process the PHP code in your pages. As far as webservers are concerned, on the Linux platform – Apache rules. It is probably the most used webserver at the moment. You can download Apache from www.apache.org. The PHP engine (release 3 or 4) can here be downloaded from www.php.net

You could learn how to configure Apache to run PHP with the help of the manual that you would be provided or you could search for articles on Tips For Linux itself.

First steps

My first PHP script consists of the classic program that displays the famous ” HELLO WORLD “. Copy the code shown below, paste and save it in a file with the name helloworld.php in your webserver standard directory (or in the webserver’s php files directory).

<HTML>
<BODY>
<?
echo ("
<H1>Hello World!</H1>

");
?>
</BODY>
</HTML>

Then start your web browser and type the following in the address bar –

http://127.0.0.1/helloworld.php

or

http://127.0.0.1/~username/helloworld.php

Note: In case you have not yet configured Apache Server you could read Article(Installing and Configuring Apache Web Server) which explains Apache Server’s configuration. Once you Apache Server is configured, you could continue with this article.

If it works correctly you can proceed and read the rest of this tutorial, otherwise you would have to do some more tweaking and get PHP configured on your machine. If you can’t solve the problem, before abandoning, try to have a look to the software documentation. Even try posting your problem on discussion forums on the Web. You will definitely find a solution.

Variables

A variable is a block of memory, accessible through a name chosen by the software developer, in which a value is stored. This value, is usually given a default value at the beginning of the application, and you can change that value during the execution of the program. PHP requires variable names to begin with the dollar ‘ $ ‘ character.

Variable names can be composed of uppercase and lowercase letters, digits and underscores. But it is not possible to include spaces or other special or reserved characters to define the names of a variable. Remember that PHP is a case-sensitive language. This means it distinguishes between uppercase and lowercase variable names. For instance, if we write the following script. The code below shows the case sensitive aspect of PHP.

<HTML>
<HEAD>
</HEAD>
<BODY>
<? $VAR1 = 5; echo ($var1); ?>
</BODY>
</HTML>

We’ll get an error message because the PHP interpreter does not find $var1 variable (The variable defined initially was $VAR1).

A script involving variable declarations and displaying the values of those variables is shown below. Read it carefully because it contains some important points that we will discuss later.

<HTML>
<BODY>
<?
$website = "http://www.bitafterbit.com";
echo ("<BR>Surf to: $website");
echo ('<BR>Surf to: $website');
?>
</BODY>
</HTML>

The program defines and prints the variable $website. Observe that in the echo() function, whose purpose is to write a string on the screen, two different kinds of inverted commas are used – they are the single and double ones.

Important: In this tutorial we will refer to the double inverted commas (“) as only inverted commas and we will refer to single inverted commas (‘) as only quotes. The main difference between these two types of syntax is that PHP interprets what is enclosed in the inverted commas, while everything appearing between quotes is considered a constant value and it is not interpreted.

The example given above produces the following output

 Surf to: http://www.bitafterbit.com
Surf to: $website

The text $website is in fact interpreted and replaced with the value of the corresponding variable only in the first echo() statement. This because in the first statement we have used inverted commas to enclose the text to print. The result of this first instruction is

 Surf to: http://www.bitafterbit.com 

As explained previously, in the second echo() statement, where quotes have been used in place of inverted commas, the enclosed text is not interpreted, because it is considered to be a constant. The output of the second echo() instruction therefore is

 Surf to: $website 

It is important to take notice of this important characteristic of PHP. It is different from other programming languages where all that appears enclosed between inverted commas is considered a constant value (a string). We will talk about strings in detail in later articles when we’ll discuss PHP’s datatypes.

A PHP Tutorial for Beginners-Part 2

Developing User Interfaces with GTK (C Programmers) – Part I

I assume you have written C programs under Linux which display their output at the terminal and now you would like to work under X as well. So you need something that will generate a user interface for you. Right.. that’s what GTK is for. It gives you ready made stuff with which you can design a user-interface quickly and easily. You don’t require to have extensive knowledge. Just the basics will help you get started and then you can learn more on your own. So in this article I shall show you a C program without a user-interface (it would do its work and display the result at the terminal) and then I would explain the program that displays the same output under X Windows.

Note: GTK stands for Gimp Toolkit. You must have heard of the much talked about software called Gimp used for image editing. The various libraries that the programmers of Gimp used were so useful that they decided to package it as a User Interface Toolkit and distribute it. Thus its called GTK, since it was originally meant only for the software GIMP.

So lets begin with GTK programming..

Here is my C program that prints a string “Hello Linux World” at the terminal. How original !! 😉

 /* hello-terminal.c */

int main(){
printf("Hello Linux World\n");
return(1);

} 

Now this is a very simple example. It just prints a string at the terminal. But its enough to start explaining GTK programming.

Now here is the modified new version that would display the same string inside a window under X.

/* hello-gtk.c */

#include &amp;lt;gtk/gtk.h&amp;gt;

gint QuitProg(GtkWidget *widget, gpointer gdata){

gtk_main_quit();
return (FALSE);

}

int main (int argc, char *argv[]){

GtkWidget *window;
GtkWidget *text_pane;

gtk_init(&amp;amp;argc, &amp;amp;argv); /*required initializing */

window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_set_usize(window,200,100);
gtk_window_set_title(GTK_WINDOW(window) , "First Program");
gtk_container_set_border_width(GTK_CONTAINER(window),5);

gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC(QuitProg), NULL);

text_pane = gtk_text_new(NULL, NULL);
gtk_text_set_editable(GTK_TEXT(text_pane) , FALSE);
gtk_container_add(GTK_CONTAINER(window) , text_pane);
gtk_widget_realize(text_pane);
gtk_text_insert(GTK_TEXT(text_pane) , NULL , NULL , NULL , " Hello Linux World \n\n" , -1);

gtk_widget_show(text_pane);
gtk_widget_show (window);

gtk_main ();

}

Phew!! seeing the above code might give you a feeling that GTK programming is not really simple after all. Just read the explanation given below once and you would no longer feel that..

Executing the GTK program:

Before we start discussing the code, for those who would be interested in getting this program to run first, here is how you compile this program. Since its a GTK based program you cannot compile it the normal way. You have to tell gcc where you can find the GTK libraries to include the necessary things.

Note: In case you do not know how to compile normal C programs under Linux, refer to Article(How to compile & execute C programs under Linux (Absolute basics))

Assuming you named the above program hello-gtk.c type the following at the prompt

$ gcc -o hello-gtk hello-gtk.c `gtk-config --cflags --libs`

Once your program compiles without any errors type the following at the prompt from within the same directory as the source file.

$ ./hello-gtk

Remember you should be working in X. You would see a nice window with the string “Hello Linux World” within that window.

Code Explanation:

Now lets discuss the lines that are not commented in the program

#include &lt;gtk/gtk.h&gt;

Without this nothing is going to work. Its the line that includes the GTK libraries in your program.

GtkWidget *window;
GtkWidget *text_pane;

These 2 lines each define a Widget of the GTK kind. One named window and the other named text_pane .

The structure of a GtkWidget is defined in the GTK libraries which you include when compiling your program.

window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

This initializes the window widget to be of the kind GTK_WINDOW_TOPLEVEL. That would mean the main outer window for an application. Always create your main window in this fashion. gtk_window_new() is a function that is already defined in the GTK libraries. It takes a few parameters. To know these parameters you would have to refer to the GTK Documentation. I cannot cover all the possible parameters in this article.

gtk_widget_set_usize(window,200,100);

This line obviously sets the size of the window specified as the first parameter to this function. In this case its the window that you just initialized. 200 would be the width and 100 would be the height.

Important: In case you aren’t familiar with any UI programming then generally the approach is that you always set all the parameters for a particular widget first and then display the widget once you have done all the settings. Thus these couple of lines that we are discussing right now doesn’t really display anything on screen. It is only setting all the parameters for this widget in the memory. Finally when we display this widget all these parameters would be used to display it correctly.

gtk_window_set_title(GTK_WINDOW(window) , "First Program");

This line sets the title of your program. This would be the text that is displayed in the title bar for any application. Here we set it to First Program.

gtk_container_set_border_width(GTK_CONTAINER(window),5);

This is a little bit of extra decoration. We set the border width to 5. Note how this function is used. The first parameter is the widget whose border width we want to set and the second parameter is the actual amount that we are setting.

Note: In non-Object Oriented languages such as C it is frequently seen that you would be passing the object on which you want to make a modification as the first parameter to a function. To site an example we could say setborderwidth(window,5) . This is just an example and not the actual function from any library. Whereas in Object Oriented Language such as C++ you might see something like window.setborderwidth(5) . These 2 examples are just made up for explanation sake and do not really exist in either of the languages. That how Object Oriented programming makes the program much easier to read and follow.

gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC(QuitProg), NULL);

This is a very important line. This line basically says that associate the delete_event for the widget named window to the QuitProg() function that is present in our program. Note that when a user clicks on the Close button for an application the delete_event is invoked. This line indicates that when such an event occurs call the QuitProg() function. The QuitProg() function in our case calls the gtk_main_quit() function that actually quits the application. In case you don’t have this line in your program you would note that the window disappears when you click on the close icon for a window but the application doesn’t yet exit from the memory. Only the front end has disappeared. Whereas the gtk_main_quit() function actually shuts down the entire application.

In case you followed the lines associated with the window widget then the following would be as easy.

text_pane = gtk_text_new(NULL, NULL);

This line creates a new text widget with no special settings. Once again please refer to the GTK documentation in case you want to figure out all the parameters you want to set.

gtk_text_set_editable(GTK_TEXT(text_pane) , FALSE);

This line makes the text widget that is going to present to be un-editable. That means the user will not be able to click inside this text widget and change the text present in that.

gtk_container_add(GTK_CONTAINER(window) , text_pane);

The line adds the text_pane widget you created inside the window widget that you had created.

gtk_widget_realize(text_pane);

I would not get into the details of the gtk_widget_realize() function , but its required for a text widget.

gtk_text_insert(GTK_TEXT(text_pane) , NULL , NULL , NULL , " Hello Linux World \n\n" , -1);

This line inserts the text into the text widget you just created. For simplicity sake so as to not overburden you with extra details, I have kept 3 of the parameters NULL and the rest are essential. Change the text to whatever you want and you will see that in the text widget.

For example you could also pass some string which you have created in your program. You could possibly use the gtk_text_insert() function within some kind of a for loop to add repeatedly to a text widget. But all this won’t be possible without more knowledge of the way the text widget works. For example there is a gtk_text_thaw() function that is required to be called whenever you want to update any text in the text widget. So in our case since the text you enter is at initialization time its doesn’t matter. But in case you are adding text after the initialization then you need to call the gtk_text_thaw() function every time you want the updated text to be displayed in the text widget. These issues may be discussed in some future article.

gtk_widget_show(text_pane);
gtk_widget_show (window);

As I had explained earlier, you would be initializing all the parameters for the widgets initially and then at last you would display these widgets. You use the gtk_widget_show() function and pass to it a widget name which you would like to be displayed.

Finally

gtk_main ();

This is the line that signals the end of the initialization and begins the process of waiting for events to take place. Events may be clicking of buttons, click of the close button for a window or any key press event. If there is an associated event handler for a event then that would be called as in our QuitProg() function that handles the delete_event, else nothing shall happen.

That’s it. I guess you must have grasped the basics of GTK programming. The important part in GTK programming is to have a reference book listing all the widgets and the associated parameters that they work with, so that you know how to configure the vast array of available widgets to suit your needs.

Customizing Emacs using the .emacs file – Part III

This is the 3rd article in the series Using Emacs. If you have followed the initial articles in this series, then you must be knowing how to use many of the features of Emacs. Emacs can be customized as much as one can possibly imagine (or rather it can be customized to an extent you couldn’t possibly imagine) . You can make Emacs respond to over 1000 different commands of yours. The power of Emacs becomes evident when you have used it for over a year and then you move to some other editor…you would sorely miss all the customizations that you have made in Emacs.

So let me explain how to make the customizations. Unlike normal commands in Emacs, all the customization is done outside Emacs. That means all the functionality that you would like to have in Emacs has to be set before you start Emacs. These customizations are stored in a file called .emacs which exists in your home directory.

Assuming your home directory is /home/david the exact location of the Emacs customization file would be /home/david/.emacs . Note the . (period) before the filename makes this file a hidden file. Use a ‘ ls -al ‘ to see this file in the directory listing. All your customizations would be placed inside this single file. When Emacs starts, it would look into this file and load all your customizations.

Believe me, once you start with this you would get addicted and you would keep on customizing Emacs to such an extent that you would no longer be satisfied with any other editor. Instead of the minimum 10 Tips per article, this time I have only 8. But they are excellent enough to make any beginner happy.

Note: For Tip No. 1 – Tip No. 26 refer to the other Articles in the Using Emacs Series.

Open your .emacs file using any text editor. Enter all the lines below as they are. The lines that begin with a ‘ ;; ‘ are comments and need not be included in your .emacs file. I have them in mine for clarity sake so that whenever I edit my .emacs I can clearly understand which command stands for what.

Tip No. 27 : Making <Delete> key work properly

In case this one was not already present in your .emacs file and you have problems with deleting text using the <Delete> key on your keyboard, then add the following lines.

;; Set up the keyboard so the <delete> key on both the regular keyboard
;; and the keypad delete the character under the cursor and to the right
;; under X, instead of the default, backspace behavior.
(global-set-key [delete] ‘delete-char)

Tip No. 28 : Using <Home> & <End> keys to move to beginning & end of lines

In case you do not like the default behavior of the <Home> and <End> keys where they take you to the beginning and end of the buffer (If you are used to the Windows behavior where they take you to the beginning and the end of the lines) then add the following. Now you shall get the keys to respond as desired.

;; [Home] & [End] key should take you to beginning and end of lines..
(global-set-key [home] ‘beginning-of-line)
(global-set-key [end] ‘end-of-line)

Tip No. 29 : Display Current Time in Emacs

This is a simple and excellent thing to do. This simply displays the current time in status bar at the bottom of the screen. When you are coding day 24-7 and lose track of time, this is the best way to remind yourself of it 😉

;; displays the time in the status bar
(display-time)

Tip No. 30 : Stop scrolling of screen at end of file

In case you have noticed, when you open a file (say it contains 20 lines), even when you reach the end of the file (the 20th line) , Emacs continues scrolling and keeps adding empty lines at the end as long as you press the <Down Arrow> Key. To avoid this and make Emacs stop the scrolling of the screen as soon as you reach the last line, add the following to your .emacs file.

;; Emacs will not automatically add new lines
(setq next-line-add-newlines nil)

Tip No. 31 : Syntax highlighting

This is probably the feature that newcomers love the most. You have heard of this and you want to get it working as soon as you can.. here it is.. this would enable coloring of the text as per the mode that Emacs works in. Thus in C mode you would get all the reserved words to be highlighted. Besides in C mode you would see a lot of other things (such as comments, etc.) getting various colors. The highlighting of the syntax makes the code easier to understand.

;; syntax highlighting by default
(global-font-lock-mode 1)

Tip No. 32 : Change the irritating yes/no questions

If you have used Emacs for even a couple of days you must be already irritated by the questions that Emacs asks to which the answer has to be a ‘yes’ or a ‘no’. Sometimes it asks a ‘y’ or a ‘n’ , but many times you are required to type the entire words ‘yes’ or ‘no’ . Adding the following line would change this default behavior and make Emacs get rid of the ‘ yes/no ‘ question permanently. Now you would only be asked the ‘ y/n ‘ question and you could simply take the required action by a single keystroke.

;; Changes all yes/no questions to y/n type
(fset ‘yes-or-no-p ‘y-or-n-p)

Tip No. 33 : Change nature of scrolling

In case you are not happy with the way Emacs scrolls through a buffer (since when it reaches the end of the screen, the buffer moves half screen upwards and the new lines appear at the middle of the screen), you could make Emacs scroll a line at a time. Thus as you reach the end of screen the buffer would move only one line upwards and continue in the same fashion rather than the abrupt 1/2 screen movement.

;; Scroll down with the cursor,move down the buffer one
;; line at a time, instead of in larger amounts.
(setq scroll-step 1)

Tip No. 34 : Stop making those ~ backups

Emacs would make a backup file whenever it edits any file. Thus you would always find a file with a similar name but ending with a ‘~’ in the same directory. In case you edit a.txt there would be a a.txt~ in the same directory. To stop this behavior add the following lines.

;; do not make backup files
(setq make-backup-files nil)

That’s all for now. Watch out for the article in which I shall be discussing customizations for C programmers using Emacs. I could have added them here, but I decided to list them in a separate article.

Using Emacs – Part II

This is the 2nd article in the Emacs series. I expect this series to continue over atleast 10 articles since there is so much about Emacs that one can discuss. The 1st article explained the basics of Emacs. You were shown how to open, close, save files and a few other tricks as well. This time I shall show you how to do much more. You would be taught effective navigation skills which would help you play around with files in a very fast and efficient manner.

I have decided to keep the no. of tips in each article in this series within the 10-15 range. A few of the tips below are a must for everyone and a few wont be really useful for beginners, but would definitely help sometime in future.

IMPORTANT: The notation used for the various keystrokes are as described below. Use this table to figure out what to press in case you cant figure out the notation used in any of the articles in this series.

<Ctrl>-Y
This means press Ctrl button and without leaving that button press Y button
<Ctrl>-YK
This means press Ctrl button and then without leaving that button press Y button and leave Y button and then press the K button. (Remember Ctrl has to be pressed throughout)
<Ctrl>-K + K
This means press Ctrl button and then without leaving that button press K button. Then leave both these buttons and then press the K button.

To view Tips No.1 – No.14 , refer to Article (Using Emacs – Part I)

Tip No. 15 : Moving to the beginning / end of sentence

While editing text in Emacs, to go to different sections of the text quickly you could use the following key strokes.

<Alt>-A would take the cursor to the beginning of the sentence (within which your cursor is present)

<Alt>-E would take the cursor to the end of the sentence (once again the sentence within which your cursor is present)

The above 2 commands are extremely useful when using the text mode of Emacs..not so useful in any of the programming modes since the beginning and ending of sentences are not clear in programming languages.

Tip No. 16 : Moving to the beginning / end of paragraph

Using the following key strokes

<Alt>-{ would take the cursor to the beginning of the current paragraph

<Alt>-} would take the cursor to the end of the current paragraph

Tip No. 17 : Moving to the beginning / end of buffer

<Alt>-< would move to the beginning of the currently open buffer (Note use the Alt key and the < key)

<Alt>-> would move to the end of the currently open buffer (Note use the Alt key and the > key)

Tip No. 18 : Deleting words

To delete words you could use the <Delete> key on the keyboard. But in case your keyboard doesn’t have a <Delete> key, in case it is some really old model or in case your <Delete> key doesn’t work, then you could use the following key strokes

<Ctrl>-D would delete a letter at the current cursor position

<Alt>-D would delete the part of the word from the current cursor position to the end of the word

This command may not work as you expect, since the characters that signify the end of a word depend on the mode that Emacs is currently in (Text Mode, HTML Mode, C Mode, etc.) Thus in Text mode a space may signify the end of a word but in C mode even a ‘ ( ‘ or a ‘ ) ‘ may indicate the end of a word.

To delete a complete word move the cursor to the first character of the word and then press <Alt>-D

Tip No. 19 : To yank previously deleted texts / Cycle through deleted texts

You must be knowing that to yank previously deleted text you have to press <Ctrl>-Y. But it is also possible to yank even the previously deleted text (the one deleted before the most recent one also)

Press <Ctrl>-Y once to yank the latest deleted stuff and then type <Alt>-Y repeatedly to yank older and older text that you had killed. The deleted text won’t be all pasted again, but as you press <Alt>-Y the yanked text would be continuously replaced with the older killed text. So its not like in case you press <Alt>-Y five times would be pasting the last five killed texts. You would actually be pasting the fifth last killed text. If you do not press <Ctrl>-Y first Emacs would warn you that the last command was not a Yank command.

Remember that this command wouldn’t work as expected every time. What text is yanked depends on how you killed the text. Whether you deleted a word or a sentence or many sentences consecutively. So I suggest you get familiar with this command yourself rather than me trying to explain all the possibilities. Use it a couple of times and you will easily get the hang of it.

Tip No. 20 : To save the current buffer as a new file

In order to Save the contents of the currently open buffer as a new file or overwrite another existing file.

<Ctrl>-XW would prompt for a new file name. You could enter an existing filename or a new filename. This command is basically equivalent to the Save-As command that exists in other editors.

Tip No. 21 : Replace contents of current buffer with a new file

To replace the current buffer with a new file use the following keystrokes
<Ctrl>-XV would prompt for a filename that you would like to open instead of the current buffer. Remember that this closes the current buffer and then opens the new file in a new buffer. It helps incase you know that you have finished work with a particular file, you could carry out the 2 tasks of closing the current file and opening a new file with a single command only.

Besides the fact that its a substitute for 2 commands, this feature may seem to be unnecessary when you can open as many files as you want in as many buffers as you like. But believe me as you start programming a lot you would be shifting between 2 buffers to modify files here and there. In that case, simple and fast switching between buffers is possible when few buffers are open. In that case when you have finished modifying a file, you would prefer replacing the buffer with a new file rather than opening a new buffer.

Tip No. 22 : Insert file into current buffer

To insert a file into the current buffer use the following

<Ctrl>-X + I would ask for a filename. On entering a filename that file would be inserted into the current buffer.

This would basically reproduce the entire contents of the given file into the current buffer at the current cursor position.

Tip No. 23 : Open a file as Read only file

To open a file in a buffer as a read only file use

<Ctrl>-XR

You could do so in case you would prefer to not accidentally edit some file but would still like to copy some part of it into another buffer. Rather than risking opening an important file in read-write mode, you could open it in read only mode.

Tip No. 24 : Cancel any command midway

In case you have already typed half of a command and then you realize that it is the wrong command, you may want to cancel that half written command. You cannot continue with the new command directly since half of the previous command has already been typed and Emacs assumes that whatever you type would be a part of that command itself. To cancel any half written command use

<Ctrl>-G

The string Quit would be displayed in the minibuffer indicating that the half typed command was canceled. You can now start typing the new command.

Tip No. 25 : How to Undo your actions

To undo any action that you have performed in Emacs use the following keystrokes

<Ctrl>-X + U

The above keystrokes would undo the last action that you performed. You could alternatively use Ctrl+ _ (to do this remember to press the Ctrl and Shift and the minus sign button together) to undo the last action.

Note: The last action need not be the last keystroke as such. I mean Emacs has a tendency to group similar consecutive keystrokes. Thus in case you typed 10 letters consecutively and then press <Ctrl>-X + U , all the 10 letters would disappear and not the 10th letter only. Since the typing of 10 letters consecutively without any other action in between is treated as one action only by Emacs.

Tip No. 26 : Jump to a particular line directly

To go to a particular line within the current buffer directly without scrolling to that location use

<Alt>-X and then the type the string goto-line followed by <Enter> then the line no. such as 30

Basically type this
<Alt>-X goto-line <Enter> 30

When you press <Enter> Emacs would display the message GOTO LINE NO in the minibuffer. Then type 30 and press <Enter> once again. Your cursor would be placed on line no. 30 in the current buffer.

That’s it for this article. A total of 12 tips which are quite useful. Yeah I know none of them were really impressive as such, but the next article will definitely show you some kewl tricks with Emacs.

Remember that learning Emacs is a lengthy process and don’t try to rush through it. As you code more and more, you would automatically find the need of more and more functionality. At that time go through these tips again and you will find them to be useful.

Installing Java under Linux

This article explains how to install Java on your Linux machine so that you can write, compile and execute Java programs on your machine. I have had extensive programming experience in Java (under Windows), so when I shifted over to Linux , the first thing I got running under Linux was Java 1.2

Procedure

1. Download the Java software from the Sun site. See to it that you download the version for Linux platform and not the Windows one. Most probably you would get the software as a tarball (.tgz). If you get it as an Windows Executable (.exe) file then you got the wrong one.

2. You can install Java in any directory. But if you want all the users to access Java then it is better to install it under the /usr/local directory.

3. I shall explain a simple way where you would extract the files from the tarball and then copy them to the /usr/local directory. Type the following command to extract the files from the original tarball

gunzip -dc jdk.x.x.x.tgz | tar xf –

5. This would extract all the files into a directory named jdk.x.x.x in the same parent directory that had the original tarball.

6. Copy this entire directory into the /usr/local directory. So you would finally have a structure as /usr/local/jdk1.2.2

7. Check that the jdkx.x.x directory has a /bin , /lib and a few other folders inside it.

8. Finally you got to add these executables (namely java, javac) to your path. Else you would have to give the absolute path every time you want to use these executables.

9. Edit the /HOME/.bash_profile file and make suitable changes to the path variable in it

PATH=/usr/local/jdkx.x.x./bin/:$PATH

10. Once you save the file then execute the file by typing the following

. $HOME/.bash_profile

11. Once this is over you can use your normal editor (Emacs is what I use) to write your Java programs and then simply type the following to compile and then run your program

# To compile your program
javac Myprogram.java
# To execute the program
java Myprogram

Now you can do all your Java coding under Linux. Happy Coding !!

Using GQ View to view Jpegs

This article explains how to use GQ View, a simple image viewing application. It is very efficient and simple to use. I have been using this viewer for a long time and I have found no problems with this application. The software does not have many settings, so I also suggest this viewer for beginners.

When you start GQ View, the screen is (by default) divided into 3 parts.

The left panel has 2 boxes, the top box displays the directory structure of your machine and the bottom box displays the contents of the selected directory.

The right panel is the region where the selected image is displayed.

Browsing Directories: To reach the directory where files are stored, use the left panel. The left panel works with single clicks. So when you click on a directory name in the upper box it opens that directory and shows its contents in the lower box.

Viewing Single Images: Once the images that you want to view are listed in the bottom box on the left panel, click on any image. This image will be displayed in the right panel. You can continue doing so for all the images..

Sequential Viewing: To view all the images in a directory sequentially, first click on the first image to display it in the right panel. Then press the Spacebar or the Backspace key to go forward or backwards in the image list. Alternatively you can use the mouse buttons. The left mouse button to go forward and the middle button to go backwards in the image list. Remember to click inside the area where the images are displayed (the right side panel).

Full Screen mode: For this mode simply press Ctrl F (when the GQ View window is highlighted). This will show the currently selected image in Full Screen mode. To go to the next image press Spacebar. And to see the previous image use the Backspace key.

Windowed Mode (without side panel): If you want to view the images only, without the side panel but NOT in Full Screen mode then click on the Float Control button (the last icon among the 9 icons that are present just above the directory selection box). This will make the side panel float . Once a particular image is displayed. You can click on this button and minimize the new panel which floats. The original window would be having the selected image. You can use the keyboard or mouse to view other images in the same directory. Spacebar / Backspace or Left / Middle mouse buttons.

Zooming: To zoom in on an image you can click on the magnifier icon with a + sign and to zoom out on an image you can click on the adjacent icon with a – sign on it. Sometimes the image is bigger than your screen and you can see only a portion of the image. Click on the 7th icon among the 9 icons (the icon in which 4 arrows point towards the sides of a square) make the image fit into the current window so that you can see the whole image at once. (Ofcourse you would be seeing a zoomed out version)

SlideShow: Check the Slideshow option which is simply excellent. Open the Options window and then select the time between the change in images (how much time each image should be on screen). Also select whether you want the slideshow to proceed in sequential or random manner, and whether you want the images to be repeated. Close the Options window, save your settings by pressing Ctlr-S. Then start your slideshow by pressing S. You can stop the slideshow by pressing S.

The Edit->Options Menu has a lot of more features which are very descriptive in nature. They are very easy to understand. So I won’t explain them over here.

The tips present in this article enable you to use GQ View effectively. You can explore other options to make maximum use of this excellent application.