PHP Notes 2

PHP Notes 2 Lakshman Gupta 8:59 AM 10/8/2019

PHP Tutorial
In the following example, four variables are automatically declared by assigning a value to them:

<?php
$number = 5;
$string1 = "this is a string\n";
$string2 = 'this is another "string"';
$real = 37.2;
?>

Strings
The string constants may be enclosed between double-quotes ( " ) or single-quotes ( ' ).
In a double-quote enclosed string, the variable conversion is done automatically.

$city = "Ankara";
print "I live in $city.";
$height = 182;
print "I am $height cm tall.";
String operators: Concatenation: . Concatenation to the end: .=
$str1 = $lastname . ", " . $firstname;
$str2 .= $str3;

Arrays
PHP supports two type of arrays:
· Numerically indexed arrays
· Associative arrays.

Numerically indexed arrays:
The indices in numerically indexed arrays starts from 0 by default, although this can be altered.
The elements of an array can be of various data types. Integers, doubles and strings can be used in the

same array.
There is no declaration of size. All arrays are dynamic in PHP.
Creation of arrays:
$ar1 = array (); // here an empty array is created.
$ar2 = array (7, 12, 20, 32); // an array with indices 0 to 3
$ar3 = array (12, "January", 2008, 16.40); // array with various data types
$ar4 = array(5 => "five", "six", "seven"); // an array with indices 5 to 7

Accessing array contents:
print $ar2[2]; // 20 is output
$ar3[2] = 2009; // value of the element with index 2 is changed
$ar1[0] = "Adana"; // an element is added to $ar1
$ar3[4] = "East"; // an element is added to $ar3
printf("7: %d, 1: %d, 'six': %s\n", $array1[3], $array2["one"], $array3[6]);
foreach ($ar3 as $v)
{ print "$v<br />"; } // all values of the array are output

Associative Arrays
Associative arrays has two part: keys and values. The keys are indices of the array.
Both the keys and values can be of any data type in the same array.
=> operator is used to combine the key and the value of an element of an associative array.

Creation of associative arrays:
$as1 = array(24 => "Ram", "Lakshman" => 844, "Pi" => 3.14159);
$as2 = array(20458444 => "Ali Ak", 20487542 => "Ayse Bal");
Accessing array contents:
print $as1["Lakshman"]; // outputs: 844
$as1[24] = "Ram"; // value of element with key=24 is changed.
$as2[20608888] = "Fatmai"; // a new element is added to array.
foreach ($as2 as $id => $name)
{ print "<b>$id</b>: $name<br />"; } // all keys and values are used
foreach ($as4 as $k => $v)
{ $as4[$k] = $v + 7; } // all values of array $as4 are increased by 7

Popular posts from this blog

Computer Fundamental In Hindi