Please style sheet are not equal in internet explorer browser Firefox, Chrome, Safari, Apple and Opera browser please visit this website.

Thank for Visit My Site and Please sent me Shayari, Status and Quotes post request.

PHP - PHP Basics, Variable, Arrays & String

PHP Basics
 
PHP Syntax
 
You cannot view the PHP source code by selecting "View source" in the browser - you will only see the output from the PHP file, which is plain HTML. This is because the scripts are executed on the server before the result is sent back to the browser.
 
Now that you are aware of how PHP scripts are executed, let's discuss how to actually write your first PHP script. All PHP scripts are written in what are called code blocks. These blocks can be embedded into HTML, if desired, and are generally defined by <?php at the start and ?> at the end.
 
NOTE
 
Although <?php and ?> are generally used,
the following are also valid code-block separators:
<? ... ?> Shorthand version of <?php and ?>

<% ... %> NOTE Although <?php and ?> are generally used, the following are also valid code-block separators:

<? ... ?> Shorthand version of <?php and ?>

<% ... %> ASP style
<SCRIPT LANGUAGE="PHP">
...
</SCRIPT>
HTML editor compatible syntax
 
Note that some of these code block separators function only when the associated php.ini configuration directive is enabled. Unless there is a specific reason not to, using the default <?php and ?> tags is strongly recommended.ASP style
 
<SCRIPT LANGUAGE="PHP">

...

</SCRIPT>
 
HTML editor compatible syntax
 
Note that some of these code block separators function only when the associated php.ini configuration directive is enabled. Unless there is a specific reason not to, using the default <?php and ?> tags is strongly recommended.
 
 
 
PHP comments
 
When programming in any language the process of adding comments involves writing notes alongside the code to describe what the code does and how it works. The comments are ignored by the PHP pre-processor when executing a script and are purely for human consumption.

In Short Comments are used as a note of the code for the help of programmer and the web developers who may view want to view source code

 
Excuses aside, there is much to be gained from included helpful and concise comments with the PHP code that powers your web site. Firstly, you will be amazed at how puzzling a section of code can be even a few months after you have written it.
 
It is not unusual for a developer to revisit some old code they once wrote and express amazement that they actually wrote it. It is important to remember that there is a good chance you will have to continue to maintain your PHP scripts long after they are written.
 
In PHP, we use // or # to make a single-line comment and /* and */ to make a large comment block.
 
PHP Single Line Comments(//,#)
 
Comments that reside on a single line are prefixed with the two forward slash characters in PHP (i.e //).
 
The following example contains a single line comment:
 
<?php

     // This is a single line comment

	 eg:<?php
	 	echo "This is to be shown";
		//This will Not be shown on the browser.
		#This will also not be shown on the browser.
		?>

?>
 
The single line comment can be on a line of its own, or it can be appended to the end of a line of code:
 
<?php

    echo "This is a test line"; // Output a line of text

?>
 
In the above example the PHP pre-processor will execute the echo statement and then ignore everything after the // single line comment marker.
 
Single line comments are also useful for temporarily highding the lines of code from the execution. For example, the following change to our previous example will cause the PHP pre-processor to ignore the entire echo command during execution:
 
<?php

    // echo "This is a test line";

?>
 
PHP Multi-line Comments
 
Multi-line comments are wrapped in /* and */ delimiters. The /* marks the start of the comment block and the */ marks the end. The following example demonstrates the use of multi-line commenting in PHP:
 
<?php

/*
   This a multi-line block
   of comments and this would not be displaed on browser.
*/

?>
 
Multi-line comments are useful when you have notes you want to make in the code that will take up more than one line. The ability to mark blocks of lines as comments avoids the necessity of placing the single line comment marker at the start of each comment line.
 
Another useful application of multi-line comments is to comment out blocks of PHP code temporarily. It is quite common to have written some PHP script and then wonder if you can re-write it so that it is perhaps more efficient or reliable.
 
In this situation you can comment out the old script fragment so that it is no longer executed and write some new code. If it turns out your new code is worse than the original (which happens from time to time) you can simply remove the new code and uncomment the old to bring it back into the execution flow.
 
 
 
PHP Operators
 

There are three types of operators. Firstly there is the unary operator which operates on only one value, for example ! (the negation operator) or ++ (the increment operator). The second group are termed binary operators; this group contains most of the operators that PHP supports.The third group is the ternary operator: ?:. It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution. Surrounding ternary expressions with parentheses is a very good idea.

The most common PHP operators are assignment operators, arithmetic operators, combined operators, comparison operators, and logical operators. Each type is discussed separately below.
 
Arithmetic Operators
 
The basic assignment operator in PHP is "=". This means that the operand to the left of "=" gets set to the value to the right of "=".
 
Arithmetic Operators
 

Operator

Description

Example

Result

+

Addition

$x=2+2

4

-

Subtraction

x=2
5-x

3

*

Multiplication

x=4
x*5

20

/

Division

15/5
5/2

3
2.5

%

Modulus (division remainder)

5%2
10%8
10%2

1
2
0

 

 

 

 

 

 

 

 

 
Assignment Operators
 

Operator

Example

Is The Same As

=

x=y

x=y

+=

x+=y

x=x+y

-=

x-=y

x=x-y

*=

x*=y

x=x*y

/=

x/=y

x=x/y

.=

x.=y

x=x.y

%=

x%=y

x=x%y

 
Comparison Operators
 

Operator

Description

Example

==

is equal to

5==8 returns false

!=

is not equal

5!=8 returns true

>

is greater than

5>8 returns false

<

is less than

5<8 returns true

>=

is greater than or equal to

5>=8 returns false

<=

is less than or equal to

5<=8 returns true

 
Logical Operators
 

Operator

Description

Example

&&

and

x=6
y=3
(x < 10 && y > 1) returns true

||

or

x=6
y=3
(x==5 || y==5) returns false

!

not

x=6
y=3
!(x==y) returns true

 
PHP Unary Operators
 
The following table outlines the various forms of pre and post increment and decrement operators, together with examples that show how the equivalent task would need to be performed without the increment and decrement operators.
 

Operator

Type

Description

Equivalent

++$var

Preincrement

Increments the variable value before it is used in rest of expression

$var = 10;
$var2 = $var + 1;

--$var

Predecrement

Decrements the variable value before it is used in rest of expression

$var = 10;
$var2 = $var - 1;

$var++

Postincrement

Increments the variable value after it is used in rest of expression

$var = 10;
$var2 = $var;
$var = $var + 1;

$var--

Postdecrement

Decrements the variable value after it is used in rest of expression

$var = 10;
$var2 = $var;
$var = $var - 1;

 
PHP String Concatenation Operator
 
Working Example
 
Given below is a PHP script that demonstrates use of some basic PHP operators:
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> PHP Operators </TITLE>
</HEAD>

<BODY>
<h2>PHP Operators </h2>
<HR>
<FIELDSET>
<LEGEND>
<span style="background-color: #3399CC; color:
#F7F7F7;font-weight: bold"> Arithmetic Operators Example</span></LEGEND> <pre> <?php #$x,$y,$result; $x=10; $y=20; //addition operator $result=$x+$y; //substraction operator echo "$x + $y =$result"; $result=$x-$y; echo "<br>$x - $y =$result"; //Multiplication operator $result=$x*$y; echo "<br>$x * $y =$result"; //division operator $result=$x/$y; echo "<br>$x / $y =$result"; $result=$x%$y; echo "<br>$x % $y =$result"; ?> </pre> </FIELDSET><BR> <FIELDSET> <LEGEND><span style="background-color: #3399CC;
color: #F7F7F7;font-weight: bold">A ssignment Operator EXAMPLE </span></LEGEND> <pre> <?php #$x,$y,$result; $x=10; $y=20; //addition operator echo "$x +=$y: "; $x+=$y; echo "$x"; //substraction operator echo "<br>$x -=$y: "; $x-=$y; echo "$x"; //Multiplication operator echo "<br>$x *=$y :"; echo "<br>$x /=$y: ". ($x/=$y); //division operator #$result=$x/$y; ?> </pre> </FIELDSET></BODY> </HTML>
 
Type the above code in the editor and save it as operator.php and now open the PHP script in the browser to view the output:
 
img
 
Try the other operators yourself.
 
 
 
PHP Execution Operator
 
All of the operators we have looked at so far are similar to those available in other programming and scripting languages. With the execution operator, however, we begin to experience the power of PHP as server side scripting environment. The execution operator allows us to execute a command on the operating system that hosts your web server and PHP module and then capture the output.
 
You can do anything in an execution operator that you could do as if you were sitting at a terminal window on the computer (within the confines of the user account under which PHP is running). Given this fact, it should not escape your attention that there are potential security risks to this, so this PHP feature should be used with care.
 
The execution operator consists of enclosing the command to be executed in back quotes (`). The following example runs the UNIX/Linux uname and id commands to display information about the operating system and user account on which the web server and PHP module are running.
(The least complicated of all three special operators is the execution operator, which is ` - a back tick. Back ticks are used very rarely in normal typing, so you might have trouble finding where yours is - it is almost certainly to the left of your 1 key on your keyboard.)
 
Note: that these command will not work if you are running a Windows based server.
 
<?php
	echo `Hello World!` . '<br>';
	echo `id`;
?>
 
This results in the following output in the browser window:
 
Linux MKDTutorialsLinuxHome 2.6.9-42.0.10.ELsmp #1 SMP Tue Feb 27 10:11:19 EST 2007 i686 i686 i386 GNU/Linux
 
uid=48(apache) gid=48(apache) groups=48(apache)
 
Sample PHP script:
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>PHP: Executing Server side Command  </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>

<BODY><H1>Executing Server Side Command </H1>
<?php
$dirToCreate="testDIR";
?>
<hr>
<FIELDSET>
	<LEGEND><span style="background-color: #3399CC
; color: #F7F7F7;font-weight: bold">
	Executing Server Side Commands </span></LEGEND>
<pre>
<?php

echo "<br>Before Executing the <i>mkdir</i> commnad";
echo `ls -la`;
echo "<hr width=75%>";
echo "<br>After Executing the <i>mkdir</i> commnad";
echo `mkdir $dirToCreate`;
echo `ls -la`;
echo "</b>";

?>
</pre>
</FIELDSET>
</BODY>
</HTML>
 
PHP script above executes some basic Linux commands and list the output in a HTML format. Type the above script and save it as serverCommand.php and uploaded it to a Linux based server to view the output:
 
img
 
Assignment
 

1. Write a PHP script to implement all Arithmetic and Assignment operators, display the output along with variable value on the browser.

2. Write a PHP script to implement Unary increment and decrement operators.

3. Write a PHP script to print following series, using Unary increment operator

 
10
9
8
.
0
 
4. Write PHP Script to implement following Unix commands:
 
a.	ls -a
b.	ls / -la
c.	mkdir hello
d.	dir /
 
 
 
Variable, Arrays & String
 
PHP Variables
 
Variables are used for storing values, such as numbers or strings , so that they can be used many times in a script.
 
A large part of writing scripts, and programming, involves the handling and manipulation of data. Data have forms, ranging from single characters, words and sentences to integers, floating point numbers and true and false values.
 
In object oriented environments such as PHP, data can also take the form of an object, a self contained module which is capable of encapsulating any number of data values of numerous different types.
 
When working with data values in PHP, we need some convenient way to store these values so that we can easily access them and make reference to them whenever required. This is where PHP variables come in to the use.
 
. Variables are used for storing a values, like text strings, numbers or arrays.
. When a variable is define can be used over and over again in your script
. All variables in PHP start with a $(Doller) sign symbol.
 
Variable type
 
As you've seen, variables begin with a dollar sign ($) and are followed by a meaningful name. The variable name cannot begin with a numeric character, but it can contain numbers and the underscore character (_). Additionally, variable names are case-sensitive, meaning that $MKDTutorials_emp and $mkdtutorials_emp are two different variables.
 
PHP is a Loosely Typed Language
 
In PHP a variable does not need to be declared before being set.
 
$var=10;
 
In the example above, you see that you do not have to tell PHP which data type the variable is.
 
. PHP automatically converts the variable to the correct data type, depending on how they are set.

. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.

. In PHP the variable is declared automatically when you use it.
 
Variable Naming
 
Variable Naming rules in PHP
 
. A variable name must start with a letter or an underscore "_"
. A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ )
. A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString)
 
Variable Scope
 
The scope is the area in which the variable is declared. In PHP, you set your scope with curly braces (the { and } characters). There are two particular types of scope, the global scope which refers to everything outside functions, and the local scope which refers to everything inside functions.Variables you declare in the global scope cannot be used in the local scope, and variables declared in the local scope cannot be used in the global scope.
 
Creating and Using Variables
 
Assigning a Value to a PHP Variable
 
Values are assigned to variables using the PHP assignment operator. The assigment operator is represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the left of the expression, followed by the assignment operator. The value to be assigned is then placed to the right of the assigment operator. Finally the line, as with all PHP code statements, is termininated with a semi-colon (;).
 
Let's begin by assigning the word "Car" to a variable named Vehicle:
 
$Vehicle = "Car";
 
We have now declared a variable with the name Vehicle and assigned a string value to it of "Car". We can similarly declare a variable to contain an integer value:
 
$rainbow_colour = 7;
 
The above assignment creates a variable named rainbow_colour and assigns it a numeric value of 7. Once a variable has been created, the value assigned to that variable can be changed at any time using the same assignment operator approach:
 
<?php

$rainbow_colour =  7; // Set initial values
$Vehicle = "Car";

$rainbow_colour =  8; // Change the initial values to new values
$Vehicle = "Bus";

?>

 
Accessing PHP Variable Values
 
Now that we have learned how to create a variable and assign an initial value to it we now need to look at how to access the value currently assigned to a variable. In practice, accessing a variable is as simple as referencing the name it was given when it was created.
 
For example, if we want to display the value which we assigned to our rainbow_colour variable we can simply reference it in our echo command:
 
<?php
echo "The colours of rainbow is $rainbow_colour.";
?>
 
This will cause the following output to appear in the browser:
 
The colours of rainbow is 8.
 
 
The examples we have used for accessing variable values are straightforward because we have always had a space character after the variable name. The question arises as to what should be done if we need to put other characters immediately after the variable name. For example:
 
<?php
echo "The color of the rainbow is the $rainbow_colourth";
?>
 
What we are looking for in this scenario is output as follows:
 
The color of rainbow is the 8th.
 
Unfortunately PHP will see the th on the end of the $rainbow_colour variable name as being part of the name. It will then try to output the value of a variable called $rainbow_colourth, which does not exist. This result in nothing being displayed for this variable:
 
The colour of the rainbow
 
Fortunately we can get around this issue by placing braces ({ and }) around the variable name to distinguish the name from any other trailing characters:
 
<?php
echo "The color of the rainbow  is the ${rainbow_colour}th";
?>
 
To give us the desired output:
 
The color of the rainbow is 8th.
 
Changing the Type of a PHP Variable
 
Loosely typed languages such as PHP (and JavaScript), allow the variable type to be changed at any point in the life of the variable simply by assigning a value of a different type to it. For example, we can create a variable, assign it an integer value and later change it to a string type by assigning a string to it:
 
<?php

$myNumber = 6; // variable is of integer type

$myNumber = six; // variable has now changed to string type

?>
 
The process of dynamically changing the type of a variable is known as automatic type conversion.
 
 
 
PHP String
 
A string variable is used to store and manipulate a piece of text.
 
Working with Strings
 
String variables are used for values that contains character strings. In this tutorial we are going to look at some of the most common functions and operators used to manipulate strings in PHP. After we create a string we can manipulate it.
 
A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the string "Hello World!" to a string variable called $text_str:
 
<?php
	$text_str= "Hello World!";
	echo "$text_str"	;
?>
 
Type the above code and save it as string.php and open the page in browser to view the output:
 
 
PHP - String Creation Heredoc
 
The two methods above are the traditional way to create strings in most programming languages. PHP introduces a more robust string creation tool called heredoc that lets the programmer create multi-line strings without using quotations. However, creating a string using heredoc is more difficult and can lead to problems if you do not properly code your string! Here's how to do it:
 
PHP Code:
 
<?php
$my_string = <<<STR
<a href="education.mkdtutorials.com" target="_self">
education.mkdtutorials.com</a><br /> PHP Tutorial<br /> Feel the power of PHP STR; echo $my_string; ?>
 
Type the above code and save it as string-heredoc.php and open the script in browser to view the output.
 
img
 
There are a few very important things to remember when using heredoc.
 
. Use <<< and some identifier that you choose to begin the heredoc. In this example we chose STR as our identifier.

. Repeat the identifier followed by a semicolon to end the heredoc string creation. In this example that was STR;

. The closing sequence STR; must occur on a line by itself and cannot be indented!
 
Another thing to note is that when you output this multi-line string to a web page, it will not span multiple lines because we did not have any <br /> tags contained inside our string! Here is the output made from the code above.
 
PHP String Manipulation
 
Simple PHP string operation
 
Using the strlen() function
 
The strlen() function is used to find the length of a string.
 
Syntax:
 
int strlen ( string str )
 
Let's find the length of our string "Hello world!":
 
<?php
    echo strlen("MKDTutorials education team.");
?>
 
The output of the code above will be:
 
20
 
The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)
 
Using the strpos() function
 
The strpos() function is used to search for a string or character within a string.
 
Syntax:
 
int strpos ( string haystack, string needle [, int offset] )
 
If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.
 
Let's see if we can find the string "world" in our string:
 
<?php
echo strpos("MKDTutorials education team.", "team");
?>
 
The output of the code above will be:
 
15
 
As you see the position of the string "team" in our string is position 15. The reason that it is 15, and not 16, is that the first position in the string is 0, and not 1.
 
<BODY>
<h3>strlen function</h3>
<hr>
<?php
$txt="MKDTutorials education team.";

echo "Length of $txt=". strlen($txt);
?>
<hr>
<h3>strpos function</h3>
<hr><?php
$txt="MKDTutorials education team.";

echo "Position of team in  $txt=". strpos($txt,"team");
?>
</BODY>
 
Type the above code and save it as str-function.php and open the script in browser, to view the output.
 
img
 
The Concatenation Operator
 
There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together.
 
Syntax:
 
$var=$var1. $var2;
 
To concatenate two variables together, use the dot (.) operator:
 
<?php
$txt1="Hello World";
$txt2="MKDTutorials Education Team";
echo "String 1= ".$txt1."<br >String =" . 
$txt2."<br />String 1 . String 2 =".$txt1." ".$txt2; ?>
 
The output of the code above will be:
 
Hello World MKDTutorials Education Team
 
If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string. Between the two string variables we added a string with a single character, an empty space, to separate the two variables.
 
 
 
PHP Arrays
 
An array is a data structure that stores one or more values in a single value. For experienced programmers it is important to note that PHP's arrays are actually maps (each key is mapped to a value).
 
PHP Arrays provide a way to group together many variables such that they can be referenced and manipulated using a single variable. An array is, in many ways, a self-contained list of variables.
 
Once an array has been created items can be added, removed and modified, sorted and much more. The items in an array can be of any variable type, and an array can contain any mixture of data types - it is not necessary to have each element in the array of the same type.
 
What is an array?
 
When working with PHP, sooner or later, you might want to create many similar variables.
 
Arrays are special data types. Despite of other normal variables an array can store more than one value. Let's suppose you want to store basic colors in your PHP script. You can construct a small list from them like this: Color list: * red * green * blue * black * white It is quite hard, boring, and bad idea to store each color in a separate variable. It would be very nice to have the above representation almost as it is in PHP. And here comes array into play. The array type exists exactly for such purposes. So let's see how to create an array to store our color list.
 
There are three different kind of arrays:
 
. Numeric array - An array with a numeric ID key
. Associative array - An array where each ID key is associated with a value
. Multidimensional array - An array containing one or more arrays
 
Creating a PHP Array
 
Arrays are created using the array() function. The array() function takes zero or more arguments and returns the new array which is assigned to a variable using the assigment operator (=). If arguments are provided they are used to initialize the array with data.
 
PHP arrays grow and shrink dynamically as items are added and removed so it is not necessary to specify the array size at creation time as it is with some other programming languages.
 
We can create an empty array as follows:
 
<?php
      $citylist = array();
?>
 
Alternatively, we can create an array pre-initialized with values by providing the values as arguments to the array() function:
 
<?php
      $citylist = array("Noida", "Delhi", "Raipur", "Ambikapur", "Bhagalpur");
?>
 
Accessing Elements in a PHP Array
 
The elements in a PHP numerical key type array are accessed by referencing the variable containing the array, followed by the index into array of the required element enclosed in square brackets ([]). We can extend our previous example to display the value contained in the second element of the array (remember that the index is zero based so the first element is element 0):
 
<?php
	$citylist = array("Noida", "Delhi", "Raipur", "Ambikapur", "Bhagalpur");
        echo $citylist[1];
?>
 
The above echo command will output the value in index postion 1 of the array, in this case Output will be:
 
Delhi
 
Manipulating Array
 
Changing, Adding and Removing PHP Array Elements
 
An array element can be changed by assigning a new value to it using the appropriate index key.
 
For example, to change the first element of an array:
 
<?php
$citylist = array("Noida", "Delhi", "Raipur", "Ambikapur", "Bhagalpur");
echo "<br> Before changing the Array, element [0] :  ".$citylist[0];
$citylist[0]= "Faridabad";
echo "<br> After changing the Array , element [0] :  ".$citylist[0];
?>
 
Output:
 
img
 
A new item can be added to the end of an array using the array_push() function. Push one or more elements onto the end of array
 
Syntax:
 
int array_push ( array array, mixed var [, mixed ...] )
 
array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. This function takes two arguments, the first being the name of the array and the second the value to be added:
 
Example:
 
<?php
$citylist = array("Noida", "Delhi", "Raipur", "Ambikapur", "Bhagalpur");
echo "Before changing the Array<pre>";
print_r($citylist);
array_push($citylist, "Gurgaon");
echo "</pre><br> After changing the Array<br><pre>";
print_r($citylist);
echo "</pre>";
?>
 
Output:
 
img
 
The first element of the array can be removed of the array using the array_shift() function, shifts the first value of the array off and returns it, shortening the array by one element and moving everything down..
 
Syntax:
 
mixed array_shift ( array )
 
<?php
$citylist = array("Noida", "Delhi", "Raipur", "Ambikapur", "Bhagalpur");
echo "Before Removing the element [0] from array";
echo "<pre>";
print_r($citylist);
echo "</pre>";
array_shift($citylist);// Add Gurgaon to start of array
echo "After Removing the element [0] from array";
echo "<pre>";
print_r($citylist);
echo "</pre>";
?>
 
Output:
 
Before Removing the element [0] from array
Array
(
    [0] => Noida
    [1] => Delhi
    [2] => Raipur
    [3] => Ambikapur
    [4] => Bhagalpur
)
After Removing the element [0] from array
Array
(
    [0] => Delhi
    [1] => Raipur
    [2] => Ambikapur
    [3] => Bhagalpur
)
 
The last item added to an array can be removed from the array using the array_pop() function.
 
Syntax:
 
mixed array_pop ( array array )
 
The following example removes the last element added:
 
<?php
$citylist = array("Noida", "Delhi", "Raipur", "Ambikapur", "Bhagalpur");
echo "Original Array";
echo "<pre>";
print_r($citylist);
echo "</pre>";
array_push($citylist, "Jaipur"); // Add Jaipur to end of array
echo "After Adding an element to the array";
echo "<pre>";
print_r($citylist);
echo "</pre>";
array_pop($citylist); // Remove Jaipur from the end of the array
echo "After Removing an element from array";
echo "<pre>";
print_r($citylist);
echo "</pre>";
?>
 
Output:
 
Try it yourself!
 
An element can be added to the start of the array by using array_unshift() function:
 
<?php
$citylist = array("Noida", "Delhi", "Raipur", "Ambikapur", "Bhagalpur");
echo "Before Removing the element [0] from array";
echo "<pre>";
print_r($citylist);
echo "</pre>";
array_shift($citylist);// Add Gurgaon to start of array
echo "After Removing the element [0] from array";
echo "<pre>";
print_r($citylist);
echo "</pre>";
array_unshift($citylist,"Mumbai") ;
echo "After Adding Mumbai to the start of the array";
echo "<pre>";
print_r($citylist);
echo "</pre>";
?>
 
Output:
 
Original Array
Array
(
    [0] => Noida
    [1] => Delhi
    [2] => Raipur
    [3] => Ambikapur
    [4] => Bhagalpur
)
After Removing the element [0] from array
Array
(
    [0] => Delhi
    [1] => Raipur
    [2] => Ambikapur
    [3] => Bhagalpur
)
After Adding Mumbai to the start of the array
Array
(
    [0] => Mumbai
    [1] => Delhi
    [2] => Raipur
    [3] => Ambikapur
    [4] => Bhagalpur
)
 
Looping through PHP Array Elements
 
It is often necessary to loop through each element of an array to either read or change the values contained therein. There are a number of ways that this can be done.
 
One such mechanism is to use the foreach loop. The foreach loop works much like a for or while loop and allows you to iterate through each array element. There are two ways to use foreach. The first assigns the value of the current element to a specified variable which can then be accessed in the body of the loop.
 
The syntax for this is:
 
foreach ($arrayName as $variable)
 
For example:
 
<?php
$citylist = array("Noida", "Delhi", "Raipur", "Ambikapur", "Bhagalpur");

      foreach ($citylist as $city)
      {
          echo "$city <br>";
      }
?>
 
Will result in the following output:
 
Noida
Delhi
Raipur
Ambikapur
Bhagalpur
 
For associative arrays the foreach keyword allows you to iterate through both the keys and the values using the following syntax:
 
foreach ($arrayName as $variable)
 
For example:
 
<?php
      $employees = array('empName'=>
'Sanjay Singh', 'empAddr'=>'1 The Street',
'accountNumber'=>'123456789'); echo "<pre>Employee Name
Address A/C No" foreach ($employees as $key=>$value) { echo " $key = $value<br>"; } </pre> ?>
 
Output:
 
Try it yourself
 
 
 
Explode and Implode
 
The PHP function explode lets you take a string and blow it up into smaller pieces. For example, if you had a sentence, which contains name of 5 persons, you could ask explode to use the sentence's commas "," as dynamite and it would blow up the sentence into separate words, which would be stored in an array. The sentence "Ram, Ravish, Rajeev, Rakesh, Ramesh" would look like this after explode got done with it:
 
Explode is a PHP function which let as divide a string into smaller pieces,explode is used to break up a string into chunks, it acts on a string, and returns an array.
Ram
Ravish
Rajeev
Rakesh
Ramesh
 
The explode() function breaks a string into an array.
 
Syntax
 
array explode(separator,string,limit)
 
Parameter Description Required/Optional
separator Specifies where to break the string Required.
string The string to split. Required.
limit Indicates t he maximum number of array elements to return Optional
 
For example to break a string $str, separated by , the syntax would be:
 
 
explode (",",$str);
 
Example:
 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>PHP Tutorial: Working with String</title>
</head>
<body>

<?php
	$str="Ram,Ravish,Rajeev,Rakesh,Ramesh";
	$arr=explode(",",$str);
?>
<pre>
<?php
echo "Original String :".$str."<br>";
echo "Exploded Array\n<br>";
	print_r($arr);

?>
</pre>
</body>
</html>
 
 
When executed the above script will display following output:
 
img
 
You can also use foreach loop to print the content of array.
 
Implode
 
The implode works exactly opposite of explode function. The PHP function implode operates on an array and is known as the "undo" function of explode. If you have used explode to break up a string into chunks or just have an array of stuff you can use implode to put them all into one string.
 
The implode function accepts to arguments: separator and the array
 
Syntax:
 
implode(separator,array)
 
Parameter Description
separator Optional. Specifies what to put between the array elements. Default is "" (an empty string)
array Required. The array to join to a string
 
 
Example:
 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>PHP Tutorial: Working with String</title>
</head>
<body>

<?php
	$arr=array("Ram","Ravish","Rajeev","Rakesh","Ramesh");
	$str=implode(",",$arr);
?>
<pre>
<?php
	echo $str;
?>
</pre>
</body>
</html>
 
 
 
On execution above script produces the following output:
 
img
 
Assignment
 
1. Convert the following String to Array "Hello, World!; Welcome, to MKDTutorials Education; Thanks for visiting" first convert the string to Array by using ";" as separator, then using "," as separator and finally using space " "

2. Convert the following Array to String: $my_arr1=array("Mika", "Mona", "Mitali", "Madhu", "Megha", "Meghna");
 
 
 

SHARE THIS PAGE

0 Comments:

Post a Comment

Circle Me On Google Plus

Subject

Follow Us