Powered by Blogger.

Variables


There’s a simple metaphor that will help you understand what PHP variables are all
about. Just think of them as little (or big) matchboxes! That’s right—matchboxes that
you’ve painted over and written names on.
String variables
Imagine you have a matchbox on which you have written the word username. You then
write Fred Smith on a piece of paper and place it into the box (see Figure 3-2). Well,
that’s the same process as assigning a string value to a variable, like this:
$username = "Fred Smith";
Figure 3-2. You can think of variables as matchboxes containing items
The quotation marks indicate that “Fred Smith” is a string of characters. You must enclose
each string in either quotation marks or apostrophes (single quotes), although
there is a subtle difference between the two types of quote, which is explained later.
When you want to see what’s in the box, you open it, take the piece of paper out, and
read it. In PHP, doing so looks like this:
echo $username;
Or you can assign it to another variable (photocopy the paper and place the copy in
another matchbox), like this:
$current_user = $username;
50 | Chapter 3: Introduction to PHP
Basic Syntax
PHP is quite a simple language with roots in C and Perl, yet it looks more like Java. It
is also very flexible, but there are a few rules that you need to learn about its syntax and
structure.
Semicolons
You may have noticed in the previous examples that the PHP commands ended with a
semicolon, like this:
$x += 10;
Probably the most common cause of errors you will encounter with PHP is forgetting
this semicolon. This causes PHP to treat multiple statements like one statement, which
it is unable to understand, prompting it to produce a Parse error message.
The $ symbol
The $ symbol has come to be used in many different ways by different programming
languages. For example, if you have ever written in the BASIC language, you will have
used the $ to terminate variable names to denote them as strings.
In PHP, however, you must place a $ in front of all variables. This is required to make
the PHP parser faster, as it instantly knows whenever it comes across a variable. Whether
your variables are numbers, strings, or arrays, they should all look something like those
in Example 3-3.
Example 3-3. Three different types of variable assignment
<?php
$mycounter = 1;
$mystring = "Hello";
$myarray = array("One", "Two", "Three");
?>
Your PHP program is responsible for passing back a clean file suitable for display in a
web browser. At its very simplest, a PHP document will output only HTML. To prove
this, you can take any normal HTML document such as an index.html file and save it
as index.php, and it will display identically to the original.
To trigger the PHP commands, you need to learn a new tag. The first part is:
<?php
The first thing you may notice is that the tag has not been closed. This is because entire
sections of PHP can be placed inside this tag, and they finish only when the closing part
is encountered, which looks like this:
?>
A small PHP “Hello World” program might look like Example 3-1.
Example 3-1. Invoking PHP
<?php
echo "Hello world";
?>
The way you use this tag is quite flexible. Some programmers open the tag at the start
of a document and close it right at the end, outputting any HTML directly from PHP
commands.
Others, however, choose to insert only the smallest possible fragments of PHP within
these tags wherever dynamic scripting is required, leaving the rest of the document in
standard HTML.
The latter type of programmer generally argues that their style of coding results in faster
code, while the former says that the speed increase is so minimal that it doesn’t justify
the additional complexity of dropping in and out of PHP many times in a single
document.
As you learn more, you will surely discover your preferred style of PHP development,
but for the sake of making the examples in this book easier to follow, I have adopted the
approach of keeping the number of transfers between PHP and HTML to a minimum—
generally only once or twice in a document.
By the way, there is a slight variation to the PHP syntax. If you browse the Internet for
PHP examples, you may also encounter code where the opening and closing syntax
looks like this:
<?
echo "Hello world";
?>

We’re going to cover quite a lot of ground in this section. It’s not too difficult, but I
recommend that you work your way through it carefully, as it sets the foundation for
everything else in this book. As always, there are some useful questions at the end of
the chapter that you can use to test how much you’ve learned.
Using Comments
There are two ways in which you can add comments to your PHP code. The first turns
a single line into a comment by preceding it with a pair of forward slashes, like this:
// This is a comment
This version of the comment feature is a great way to temporarily remove a line of code
from a program that is giving you errors. For example, you could use such a comment
to hide a debugging line of code until you need it, like this:
// echo "X equals $x";
You can also use this type of comment directly after a line of code to describe its action,
like this:
$x += 10; // Increment $x by 10
When you need multiple-line comments, there’s a second type of comment, which looks
like Example 3-2.
Example 3-2. A multiline comment
<?php
/* This is a section
of multiline comments
which will not be
interpreted */
?>
You can use the /* and */ pairs of characters to open and close comments almost
anywhere you like inside your code. Most, if not all, programmers use this construct to
temporarily comment out entire sections of code that do not work or that, for one reason
or another, they do not wish to be interpreted.
#include <stdio.h>
 
int main()
{
   int n, sum = 0, c, array[100];
 
   scanf("%d", &n);
 
   for (c = 0; c < n; c++)
   {
      scanf("%d", &array[c]);
      sum = sum + array[c];
   }
 
   printf("Sum = %d\n",sum);
 
   return 0;
}
/*
Output ::
5 4 3 2 1 
Sum = 15
*/
#include <stdio.h>
 
int main()
{
   int n, sum = 0, c, value;
 
   printf("\nEnter the number of integers you want to add :: ");
   scanf("%d", &n);
 
   printf("\nEnter %d integers :: ",n);
 
   for (c = 1; c <= n; c++)
   {
      scanf("%d",&value); 
      sum = sum + value;
   }
 
   printf("\nSum of entered integers :: %d",sum);
 
   return 0;
}
/*
Output ::
Enter the number of integers you want to add :: 5
Enter 5 integers :: 5 4 3 2 1
Sum of entered integers :: 15
*/
#include<stdio.h>
 
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
 
main()
{
   int n, r;
   long ncr, npr;
 
   printf("\nEnter the value of n and r :: ");
   scanf("%d%d",&n,&r);
 
   ncr = find_ncr(n, r);
   npr = find_npr(n, r);
 
   printf("%dC%d = %ld\n", n, r, ncr);
   printf("%dP%d = %ld\n", n, r, npr);
 
   return 0;
}
 
long find_ncr(int n, int r)
{
   long result;
 
   result = factorial(n)/(factorial(r)*factorial(n-r));
 
   return result;
}
 
long find_npr(int n, int r)
{
   long result;
 
   result = factorial(n)/factorial(n-r);
 
   return result;
} 
 
long factorial(int n)
{
   int c;
   long result = 1;
 
   for( c = 1 ; c <= n ; c++ )
      result = result*c;
 
   return ( result );
}
/*
Output ::
Enter the value of n and r :: 5 2
5c2 = 10
5p2 = 20 
*/
#include <stdio.h>
#include <stdlib.h>
 
char *decimal_to_binary(int);
 
main()
{
   int n, c, k;
   char *pointer;
 
   printf("\nEnter an integer in decimal number system :: ");
   scanf("%d",&n);
 
   pointer = decimal_to_binary(n);
   printf("\nBinary string of %d is :: %s\n", n, t);
 
   free(pointer);
 
   return 0;
}
 
char *decimal_to_binary(int n)
{
   int c, d, count;
   char *pointer;
 
   count = 0;
   pointer = (char*)malloc(32+1);
 
   if ( pointer == NULL )
      exit(EXIT_FAILURE);
 
   for ( c = 31 ; c >= 0 ; c-- )
   {
      d = n >> c;
 
      if ( d & 1 )
         *(pointer+count) = 1 + '0';
      else
         *(pointer+count) = 0 + '0';
 
      count++;
   }
   *(pointer+count) = '\0';
 
   return  pointer;
}

/*
Output ::
Enter an integer in decimal number system :: 5
Binary string of 5 is :: 
*/
#include <stdio.h>
 
int main()
{
  int n, c, k;
 
  printf("\nEnter an integer in decimal number system ::");
  scanf("%d", &n);
 
  printf("\n%d in binary number system is ::", n);
 
  for (c = 31; c >= 0; c--)
  {
    k = n >> c;
 
    if (k & 1)
      printf("1");
    else
      printf("0");
  }
 
  printf("\n");
 
  return 0;
}

/*
Output :
 Enter an integer in decimal number system :: 5
 5 in binary number system is :: 101
*/
#include <stdio.h>
 
long gcd(long, long);
 
int main() {
  long x, y, hcf, lcm;
 
  printf("Enter two integers :");
  scanf("%ld%ld", &x, &y);
 
  hcf = gcd(x, y);
  lcm = (x*y)/hcf;
 
  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);
 
  return 0;
}
 
long gcd(long x, long y) {
  if (x == 0) {
    return y;
  }
 
  while (y != 0) {
    if (x > y) {
      x = x - y;
    }
    else {
      y = y - x;
    }
  }
 
  return x;
}
/*
Output :
Enter two integers : 5
10
Greatest common divisor of 5 and 10 = 5
Least common multiple of 5 and 10 = 10
*/

#include <stdio.h>
 
long gcd(long, long);
 
int main() {
  long x, y, hcf, lcm;
 
  printf("Enter two integers :");
  scanf("%ld%ld", &x, &y);
 
  hcf = gcd(x, y);
  lcm = (x*y)/hcf;
 
  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);
 
  return 0;
}
 
long gcd(long a, long b) {
  if (b == 0) {
    return a;
  }
  else {
    return gcd(b, a % b);
  }
}
/*
Output :
Enter two integers :5
10
Greatest common divisor of 5 and 10 = 5
Least common multiple of 5 and 10 = 10
*/ 

#include<stdio.h>
 
long factorial(int);
 
int main()
{
  int n;
  long f;
 
  printf("Enter an integer to find factorial :");
  scanf("%d", &n); 
 
  if (n < 0)
    printf("Negative integers are not allowed.\n");
  else
  {
    f = factorial(n);
    printf("Factorial od %d = %d", n, f);
  }
 
  return 0;
}
 
long factorial(int n)
{
  if (n == 0)
    return 1;
  else
    return(n * factorial(n-1));
}
/*
Output :
Enter an integer to find factorial : 5
Factorial od 5 = 120
*/
#include <stdio.h>
 
long factorial(int);
 
int main()
{
  int number;
  long fact = 1;
 
  printf("Enter a number to calculate it's factorial :");
  scanf("%d", &number);
 
  printf("Factorial of %d = %d",number,result);
 
  return 0;
}
 
long factorial(int n)
{
  int c;
  long result = 1;
 
  for (c = 1; c <= n; c++)
    result = result * c;
 
  return result;
}
/*
Output :
Enter a number to calculate it's factorial : 5
#include <stdio.h>
 
int main()
{
  int c, n, fact = 1;
 
  printf("Enter a number to calculate it's factorial:");
  scanf("%d", &n);
 
  for (c = 1; c <= n; c++)
    fact = fact * c;
 
  printf("Factorial of %d = %d\n", n, fact);
 
  return 0;
}
/*
Output :
Enter a number to calculate it's factorial: 5
Factorial of 5 = 120
*/
#include <stdio.h>
 
int main()
{
   int n, sum = 0, remainder;
 
   printf("Enter an integer :");
   scanf("%d",&n);
 
   while(n != 0)
   {
      remainder = n % 10;
      sum = sum + remainder;
      n = n / 10;
   }
 
   printf("\nSum of digits of entered number = %d\n",sum);
 
   return 0;
}
/*
Output: 
Enter an integer : 12345
Sum of digits of entered number = 15
*/
#include <stdio.h>
 
int main()
{
  int year;
 
  printf("Enter a year to check if it is a leap year : ");
  scanf("%d", &year);
 
  if ( year%400 == 0)
    printf("%d is a leap year.\n", year);
  else if ( year%100 == 0)
    printf("%d is not a leap year.\n", year);
  else if ( year%4 == 0 )
    printf("%d is a leap year.\n", year);
  else
    printf("%d is not a leap year.\n", year);  
 
  return 0;
}

/*
Output : #1
Enter a year to check if it is a leap year : 2010
2010 is not a leap year.
Output : #2
Enter a year to check if it is a leap year : 2012
2012 is a leap year.
Output : #3
Enter a year to check if it is a leap year : 2000
2000 is a leap year.
Output : #4
Enter a year to check if it is a leap year : 2100
2100 is not a leap year.
*/
#include <stdio.h>

int main()
{
  char ch;
  int flg;

  printf("Input a character : ");
  scanf("%c",&ch);
  flg=check_vowel(ch);
  if(flg==1)
  printf("%c is a vowel",ch);
  else
  printf("%c is not a vowel",ch);
  return 0;
}
int check_vowel(char a)
{

    if (a=='a'||  a == 'e'||  a == 'i'||  a == 'o'||  a == 'u'||a=='A'||  a == 'E'||  a == 'I'||  a == 'O'||  a == 'U')
       return 1;

    return 0;
}

/*
Output : #1
Input a character :A
A is a vowel

Output : #2
Input a character :x
x is not a vowel
*/
#include <stdio.h>
 
int main()
{
  char ch;
 
  printf("Input a character : ");
  scanf("%c", &ch);
 
  switch(ch)
  {
    case 'a':
    case 'A':
    case 'e':
    case 'E':
    case 'i':
    case 'I':
    case 'o':
    case 'O':
    case 'u':
    case 'U':
      printf("%c is a vowel.\n", ch);
      break;
    default:
      printf("%c is not a vowel.\n", ch);
  }              
 
  return 0;
}


/*
Output : #1
Input a character : A
A is a vowel. 
Input a character : x
x is not a vowel.
*/