Friday 31 May 2013

String Operators and Functions in PHP

Strings are used for values that contain a character or group of characters.
As earlier told Strings can be represented in 3 ways : double quotes, single quotes and heredoc.
For more info check out the string datatype in earlier post: http://php-revisited.blogspot.in/2013/05/php-data-types.html

More detailed description can be be Found herePHP MANUAL

Now let us move on To String operators and common functions

String Operators
There are two String Operators in PHP.


  1. Concatenation Operator
To concatenate strings in PHP we use the operator "." (quotes for clarity) .

Example:

<?php
$txt1="Hello world!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>

Output:

      2.  Concatenating assignment operator 

This operator appends the argument on the right side to the argument on the left side. It is represented by '.='(quotes for clarity).

Example:

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
echo $b.'<br>';
$a = "Hello ";
$a .= "World Howz U All!";     // now $a contains "Hello World Howz U All!"
echo $a;
?>

Output:

String Based Functions in PHP

We would here talk only about three basic and most commonly used String functions in PHP. Though there are many string related functions but most of them are not commonly used in basic designing procedure. 

Though if you have any problem related to any one other function feel free to post a comment and ask questions about it and i would try to reply to them as soon as possible.:)
You can get more info about them you by visiting Link1 or Link2

1. strlen()
    This is the most commonly used function. This is  used to find the length of a string. This function can be used with PHP loops to loop through a string.

Example:

<?php
$app="This is a Good Blog";
echo "THE LENGTH OF STRING IS:-->".strlen($app);
?>

Output:
2. strpos()
    The strpos function is used to search for a string or character within a string. 
If a match is found in the string this function returns the position of the first match. If no match is found it will return FALSE.

Example:

<?php
$a="This is great Blog";
$b="This is great great Blog";
echo strpos($a,"great").'<br>';
echo strpos($b,"great").'<br>';
if(strpos($b,"ok")==FALSE)
echo "NOT FOUND";
?>

Output:

3. strcmp()
     int strcmp ( string $str1 , string $str2 )

    This is used to compare two strings and Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. ie:

If $str1 == $str2 strcmp return 0.
If $str1  > $str2 strcmp return 1.
If $str1  < $str2 strcmp return -1.

This is case sensitive compare.

Example:

<?php
$a="This is Good Blog";
$b="This is Good Blog";
$c="this is Good Blog";
if( strcmp($a,$b) ==0) //returns 0 in this case as both are same
echo "They are equal".'<br>';
if( strcmp($a,$c)==0 ) //case sensitive compare
echo "They are equal".'<br>';
else
echo "They are not equal".'<br>';
?>

Output:


So This was all about string u can get more at PHP STRING and STRING FUNCTIONS or you could simply post a comment and ask questions to me which i would like to answer as fast as possible.

Thursday 30 May 2013

Type Casting In PHP

Since due to its similarity with languages like C and C++ it has Type Casting similar to C and C++.

General example Type Cast a integer to string is:

<?php
$a=20;
$b=(string)$a;//Type Casting Format
?>

 Similarly we can use (int) or (integer) to type cast to integer, (bool) or (boolean) to type cast to Boolean, (float) or (double) or (real) to cast to float, (array) to cast to array and so on for other data types also.

Thing to note is that variable to string Type Casting can be done also by enclosing it within double quotes. Example :

<?php
$a=20;
$str1="$a"; //first Type Casting method
$str2=(string)$a; //second Type Casting method
echo $str1."<br>".$str2;
?>

Output Of this Type Casting script on browser would be :
gettype()
This simply tells what is the type of the variable we have used.
Example:

<?php
$a=TRUE; //boolean 
$b=12; //Integer
$c="12"; //String
$d=12.64; //float
$e="ok"; //String
echo gettype($a).'<br>'.gettype($b).'<br>'.gettype($c).'<br>'.gettype($d).'<br>'.gettype($e);
?>
 Output would be

is_type(variable)
This function simply returns True(1) or False(0) checking the datatype as per the purposed type.
is_int(variable)
is_float(variable)
is_string(variable)
is_boolean(variable)
being some of the functions to check whether matches given data type
Example:
<?php
$a="12"
echo is_string($a);
?>

Output is 
settype()
The settype() function is used to set the type of a variable.
Syntax :  settype(var_name, var_type)

Parameters:


*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

It returns value True or False on success and failure respectively.Hence it has Boolean type

Example:
<?php
$a=12;
$b="12";
settype($a, "string");
settype($b, "integer");
echo $a.'<br>';
echo $b.'<br>';
echo gettype($a).'<br>';
echo gettype($b);
?>

Output would be 

var_dump()
Provides methods for dumping structured information about a variable.The var_dump function displays structured information about expressions that includes its type and value. Arrays are explored recursively with values indented to show structure.

Example:

<?php
$b = 3.1;
$c = true;
var_dump($b, $c);
?>

Output will be:






Wednesday 29 May 2013

PHP Data Types

So now lets move on to some data type knowledge in PHP.
PHP basically supports 8 Data types namely being :
  1. Boolean 
  2. Integer
  3. Float 
  4. String
  5. Array
  6. Object
  7. Resource 
  8. Null
The Array and Object are known as Compound Data Types and Resource and Null are known as Special Data Types whereas remaining 4 are primitive scalar data types

We shall see each one of them one by one

Boolean

This is the easiest data type and needs no introduction. It can either have True or False value.
Special to note is that both True and False are Case Sensitive.

<?php
$foo=True;
echo $foo;
?>

  would simply produce 1 as Output.

Integers 
Integer can range from {....,-1,0,1,2,...}

In PHP we can assign integers in 10 based(decimal), 16 based(hexadecimal), 8 based(octal) notation which can have + or - sign at start.

<?php
$a1=12 ; //decimal number
$a2=-123; //negative number
$a3= 0123; //octal based number 
$a4= 0x1A; //hexadecimal based number
echo $a1." ".$a2." ".$a3." ".$a4;
?>

This gives Output as under 


Floating Point Numbers
They can be specified as below 

<?php
$a1=1.23;
$a2=1.2e3;
$a3=6E-12;
?>

The size of float depends on the platform we use.(Google it for more Info :) )

Strings
As we all knows string is sequence of characters. PHP has no bound for strings.
There are 3 ways to represent Strings in PHP
1. Single Quotes : This is the most commonly used methodology. But here to specify a literal one will need it to be preceded by backslash (\).
Eg    echo 'OK :\\*';
would give OK :\* as output .

2. Double Quotes : This is another most common used string displaying methodology here PHP understand more special characters like \n, \r etc.

>>>More Difference and information on Both Single and Double Quotes could be found hereDetails

3. Heredoc : Its another way to delimit strings having syntax as <<< . 

General syntax is :

<?php 
<<< Identifier String  Identifier;
?>

eg:-


<?php 
echo <<<EOT 
My name is ....
EOT;
?>

 This would give My name is .... as output .

More Info on all Delimetering String Formats could be found here : Details

Arrays
An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. In PHP unlike all other languages we can have different data type values stored in arrays. 
We would discuss about PHP arrays in detail later.

Objects
To initialize an object we use the new statement so that we can instantiate the object to variable. 
Eg: 

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo.";
    }
}

$bar = new foo;
$bar->do_foo();

?>  

Resource 
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions 

The following is a list of few functions which create, use or destroy PHP resources. 

fbsql_db_query()-Selects a database and executes a query on it.

ftp_connect()-opens an FTP connection to the specified host .

imap_open()-Open an IMAP stream to a mailbox.

NULL
It simply represents that a variable has no value.

Eg:

<?php
$make=NULL;
echo $make;
?>

The output on browser would be nothing just blank.

PHP Syntax and Basics

So now after you would have gone through the install of the IDE and web server we are now ready to start :)

 PHP Syntax

  • In PHP scripting bloc starts with <?php and end with ?> This is the basic PHP Syntax.
  • A PHP scripting block can be placed anywhere in the document. Some of the web servers like xampp also support shorthand for <?php which is <? for starting and ?>  for closing.Hence in such cases PHP Syntax becomes <? for start and ?> for end


Simple script to print My first PHP script on browser is :
<body>
<?php               //start PHP Syntax
echo "My first PHP script";
?>
</body>
</html>



  • The code in PHP must end with semicolon.The semicolon in PHP acts as separator and is used to distinguish two or more set of instructions. 
  • The echo command is one of the three most commonly use output statements use in PHP others being print and print_r. We would discuss print_r later but now lets focus on echo and print.
  • Both can be used to print on browser but the basic difference between them is that echo does not return a value but print always returns 1. Other major differences can be found here Difference .


How to Run your PHP code on browser


  • Once you write your script it becomes essential to run them on browser to test  them so in order to do so you can make a folder in  G:\xampp\htdocs (g drive in my case) or can directly save page in G:\xampp\htdocs.
  • Its better to make folder for whole project and save file there with a .php extension  and if you want to run a single page you can save it directly in mentioned htdcos folder with a .php extension .
  • In order to now see your output on browser open any of the standard browser i consider mostly Mozilla as it works best with xampp.
  • Now directly writing localhost in URL bar will open your XAMPP manager.
  • Now in order to view your file you will have to write localhost/filename (for single file stored in htdocs) or localhost/foldername/filename (for file stored in a folder in htdocs)

Comments in PHP
PHP supports comments similar to those of C and C++. 
  • For single line comment we use //
  • For multi line comment we use /* to start and a */ to end comment.

Variables in PHP 
Variables as known are the names uses to store values such as numbers and strings etc. 
  • All variables in PHP start with $ sign .
Syntax ::  $var_name=value;

Now lets see this through an example 



<?php
$txt="Hello World";
$abc= 12;
echo "$txt"."  "."$abc";
?>

Output






Variables Variables
This is one of the unique features of PHP which may appear same as use of addresses in C and C++. 
A variable variable takes the value of a variable an treats that as the name of the variable. eg 
<?php 
$a="hello";
?>

 Then if we again write the code as 

<?php
$a="hello";
$$a="world";
echo "$a"." "."$hello".'<br>'; //print 1st method
echo "$a"." "."${$a}";     //print 2nd method
 ?>

Then in this case $$a is similar to as to write $hello where $hello is a variable variable and both the methodologies of printing produce same output on browser. we use {} while using variable variable directly. as seen in the above example.

Variable Naming Rules 
  • Variable must start with _(underscore) or with a letter.
  • Variable can only contain alpha numeric characters and underscores.
  • Variable should not contain any spaces.

PHP as Loosely Typed Language
We must keep always in mind that PHP is loosely typed language. in PHP a variable does not need to be declared before being set. PHP automatically converts the variable to correct data type depending on how they are set. Unlike strongly typed languages you don't have to use datatypes to define type of the variables here.

Tuesday 28 May 2013

How to Start Using PHP

So Now I Return BACK!!!!!!!!!!

Question now arises how shall we start using PHP and make its first page. There are mainly 2 prerequisites

  1. Web Server package.
  2. PHP based IDE. (i recommend using IDE because they save time and are easy to use)
Web Server Package
I personally use xamppXAMPP  is a free and open source cross-platform web server solution stack package, consisting mainly of the Apache HTTP ServerMySQL database, and interpreters for scripts written in the PHP and Perl programming languages.
Other most common server package is WAMP

PHP based IDE
IDE are very important now days for any fast development of projects and programs. For PHP there are various available IDE and editors.
  • Top Style 5.0-Though this is html and css editor but it provide you feature to connect to other web development languages. This is my personal favorite since its best for css as well as provide PHP connections. (I would later tell you how to connect top style with PHP).
  • PHPdesigner8-This is another very popular for PHP based designing but not so good for css embedding. 
There are various other available resources with which you could start using PHP.
I personally go for Top Style 5.0 along with xampp.

Connecting Top Style with PHP
This is very easy to do once you install both top style and xampp.
  1. Open Top Style.
  2. Go to Options>Options (You could directly press F8 in case of  Top Style 5.0)
  3. See for Preview>Mappings Click it 

    4. Click on Add Button and Choose File where u have htdocs document in your xampp installation location in my case its G:\xampp\htdocs\



    5. Press Ok and Finally Press Apply To install these settings.
    Finally we are now ready to start our PHP web based development :)))

Thursday 9 May 2013

PHP What it is and Why it is used

So I Start my journey up here by saying Hello!!!! to all of you.

What is PHP?
Simply the first question arising in our minds is what is PHP.
Simple answer to it is PHP is a server scripting language, and is a powerful tool for making dynamic and interactive Web pages.It was Originally created by Rasmus Lerdorf in 1995. PHP originally stood for Personal Home Page, it now stands for PHP: Hypertext Preprocessor.
(more information about php history can be found here https://en.wikipedia.org/wiki/PHP)

Why was PHP made?
PHP development began in 1994 when the developer Rasmus Lerdorf wrote a series of Common Gateway Interface (CGI) Perl scripts, which he used to maintain his personal homepage.He rewrote these scripts in C for performance reasons, extending them to add the ability to work with web forms and to communicate with databases and called this implementation "Personal Home Page/Forms Interpreter" or PHP/FI. This implementation could be used to build simple, dynamic web applications.

Features Of PHP
  1. PHP is an open source scripting language that is designed for Web application development and enables very simple scripting. PHP is widely used for content management, database access, eCommerce, forums, blogs, wikis, and other web based applications.
  2. PHP combined with MySql are cross platform.
  3. PHP can be used on all major operating systems, including Linux, Solaris, Windows, Mac OS X, RISC OS and many more.
  4. PHP supports for most of web servers today this includes Apache, Microsoft IIS, Netscape, Personal Web Server etc. For majaority of servers PHP has a module, for the others supporting the CGI standard, PHP can work as CGI processor.
  5. PHP is easy to learn and runs efficiently on server side.
  6. PHP is free to download from the official PHP resource www.php.net .
  7. PHP can be embedded into HTML.
Benefits Of PHP over other scripting language

1: Simple and easy to learn
PHP scripting is definitely one of the easiest, scripting language to learn and grasp for developers. This is partially due to the similarities PHP syntax has with C and Java.
2: Support
Since PHP has large user base due to its growing popularity hence there is large available support for it over and through other resources.
3: Freedom
When comparing PHP to a language such as ASPX, the level of freedom you get is far superior. You can use any text editor in order to code PHP such as Notebook++, jEdit, Emacs, Bluefish, or even just Notepad if you feel inclined. If you want to develop applications with ASPX, you’re going to be limited to Microsoft Visual Studio.
4: Free
There are no costs associated with using PHP, including updates. PHP is 100% free for anyone to use.
5: Frameworks
There are large number of PHP framework available like DIY, Zoop, Yii etc.
6: Easier to fix problems
Benefit you get with PHP is that problems aren't as difficult to find and fix as they are with other languages. This is because with each request, PHP cleans up and starts over. So an issue with one request will not necessarily disrupt another.
7: Object Oriented
PHP actually has the ability to call Java and Windows COM objects. In addition to this, you can create custom classes. Other classes can actually borrow from those custom classes as well which extends the capabilities of PHP even further.
8: Speed
Since PHP does not use a lot of a system’s resources in order to run, it operates much faster than other scripting languages. Even when used with other software, PHP still retains speed without slowing down other processes.