Thursday, February 28, 2013

Operators in PHP 5.4.8

Operators in PHP 5.4.8





Airthmetic   Operators


OperatorDescriptionExampleOutput
+Additionex1: $i=1+1; $j=1.5+1.23; $k=$i+$j;2 2.73 4.73
-Minusex1: $i=1-1; $j=1.5-1.23; $k=$i+$j;0, 0.27, 0.27
*Multiplicationex1: $i=10*10; $j=1.5*1.23; $k=$i*$j;100, 1.845, 184.5
/Divisionex1: $i=1/2; $j=1.5/1.23; $k=$i/$j;0.5; 1.219512195122; 0.41
%Modulusex1:$i=8%2; $j=1.5%5.5; $k=$i%$j;0 ,1, 0
++Incrementex1: $i++; ++$j; $k=$i++ + $j++;3,4,5  (i=1,j=2)
--Decrementex1: $i--; --$j; $k=$i-- + $j--;-1, 0; 1(i=1,j=2)


Logical Operators



OperatorDescriptionExampleOutput
&&Andex1: $i=1;$j=2 ; $i==1 && $j==2true
andlow-precedence and ex1: $i=1;$j=2 ; $i==1 and $j==2true
||Orex1: $i=1;$j=2 ; $i==1 || $j==2true (it never evaluate $j==2)
because first exp is true.
orlow-precedence orex1: $i=1;$j=2 ; $i==1 or $j==2same as above ||
!Not$i=1;$j=2 ; !($i==$j)true
xorExclusive orex1: $i=1;$j=2; $i xor $j1


Comparison Operators/Relational Operators.


OperatorDescriptionExampleOutput
==is equal toex1: $i=1; $j=2; $i==$j;  false
!=not equal toex1: $i=1;$j=2; $i != $jtrue
>is greater thanex1: $i=10; $j=20; $i>$jfalse
<is less thanex1: $i=10;$j=20; $i<$jtrue
>=is greater than equal toex1:$i=8;$j=8.8; $i >= $j
false
<=is less than equal toex1: $i=8;$j=8.8; $i <= $j
true

Comments in PHP

Comments in PHP

PHP Supports single line comments as well multi-line comments.


PHP Single line comments


double back slash  //

//This is my first program in PHP

$name="shyam benegal"; //Name can contain only alphabets .this is single line comment

another example:

$city="new York";//This is my home town $zip=10027
in above line "This is home my home tow $zip=10027" will be taken as single line comment.

you never get value of $zip.

PHP Multiline comments


/*
            This is multi line comments
             in PHP file

*/  


PHP runtime interpreter ignores these lines.  Comments are meant for understanding program functionality. i.e details about each function etc.,


Tags:PHP comments, comments in PHP 5.4.8, Single line comments in PHP, Multi line comments in PHP 5.4.8

Variables in PHP

Variables in PHP

  •                 All variable names should start with alphabets or underscore(_).
  •                 Variable names are case-sensitive
  •                 Variables can only have alphabets and numbers and special character like  underscore(_).
Variables starts with dollar($) sign.

     valid variable names:  $name
                                         $Address1,
                                          $Address2,
                                          $_myCity
                                           $Full_Name
                                           $my_City

PHP is a loosely coupled language.   So an variable can hold any type of data during its lifetime.
i.e same variable can be used for string, int,float etc., At runtime PHP engine determines type of the variable.

Variable  examples


$name="Peter England";  var_dump($name);  // Output: string(13) "peter england"
$_myCity="New Jersy"; var_dump($_myCity); // Output: string(9) "New Jersy"
$Full_Name="sam uncle"; var_dump($_myCity); // Output: string(9) "sam uncle"
 $2day ="saturday";var_dump($2day);// Output: Parse error: syntax error, unexpected '2' (T_LNUMBER), expecting variable (T_VARIABLE) or '$' in 

Variable shouldn't start with numbers.

Variable can hold any type of data during its lifetime.

for ex:


$mynum ="10"; // Output:string(2) "10"
$mynum = 1+1; // Output:int(2)   , in this case $mynum is an integer variable.


Tags: variables in PHP 5.4.8,PHP Version 5.4.8, variable usage in PHP, Declaring variables in PHP,
variables syntax in PHP 5.4.8, variables in PHP.

Tuesday, February 19, 2013

Find MySQL Version


Find MySQL Version


mysql>Status;

O/P:

C:\Program Files\MySQL\MySQL Server 5.1\bin\mysql.exe  Ver 14.14 Distrib 5.1.66,
 for Win64 (unknown)

Connection id:          85
Current database:
Current user:           root@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.1.66-community MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
TCP port:               3306
Uptime:                 5 days 4 hours 26 min 15 sec


Tags:MySQL version,Find MySQL Version,Find MySQL Current Database,Find MySQL Current User,Find MySQL Server Version,Find MySQL Protocol Version,Find MySQL Connection,Find MySQL Server characterset,Find MySQL DB characterset,Find MySQL client Characterset,find MySQL Client Character Set,Find MySQL port,Find MySQL Uptime.

MySQL REVERSE String function

MySQL REVERSE String function


String REVERSE in MySQL reverses the the string.

         Syntax:    Reverse(characterSequence)

select REVERSE('Audi');

O/P:

| REVERSE('Audi') |
| iduA            |

1 row in set (0.00 sec)


Tags:MySQL REVERSE String function,Reverse String in MySQL,String Reverse in MySQL

Saturday, February 16, 2013

How to query MySQL Table using PHP

mysqli_connect connect to MySQL Server instance
mysqli_select_db select database
mysqli_query issue query to table/view/stored procedure/function.
mysqli_fetch_array fetch result set based on query. single/multiple
mysqli_error if any error occurs detailed error message will be included in this


Here I have sample EMP table
              
                             1) Database Name  "HR"
                             2) Table Name : "EMP"
                             3) EMP table has  3 columns 1.idEMP 2.ename,3.Sal



Step 1)  Connect to Database using mysqli_connect

              $link = mysqli_connect('localhost','root','password');
              HostName: Localhost
              Username:root
              Password:your password
 Note: If MySQL server instance is running under port 3306,  u can type hostname as localhost:3306

Step 2)  Select database in MySQL


             mysqli_select_db($link,'HR'))
             Here HR is the Database Name

Step 3) Issue DML query to a Table i.e EMP table

               $result=mysqli_query($link, "select * from emp");

             Query: select * from emp
             result set:  $result.

Step 4) Fetch data from Result Set
              $row=mysqli_fetch_array($result))


OUTPUT:

Emp IDEmp NameSalary
2shyam5500.56
3benegal5555.00



Here is the Complete Source Code

<?php
$link = mysqli_connect('localhost','root','password');
if(!$link)
{
   $output='Unable to connect to database server'; echo $ouput;
   exit();
}



if(!mysqli_select_db($link,'HR'))
{
     $output = 'Unable to locate the HR database.';
     echo $output;
     exit();
}



$result=mysqli_query($link, "select * from emp");
if(!$result)
{
  $error = 'Error ...'.mysqli_error($link);
  echo $error;
  exit();
}
echo "success";
$output="<table border='2' align='center'>";
$output.="<tr style='background-color:teal;color:white;'><th>Emp ID</th><th>Emp Name</th><th>Salary</th></tr>";
while($row=mysqli_fetch_array($result))
{

    $output.="<tr><td>".$row['idEMP']."</td><td>".$row['ename']."</td><td>".$row['Sal']."</td></tr>";
   
}
$output.="</table>";

echo $output,"<br>";
?>



Tags:How to query MySQL Table using PHP,Query MySQL in PHP,Connect to Database using Mysqli in PHP, Query MySQL database using PHP, Retreive mysql Database in PHP, PHP & MYSQL Query,mysqli_fetch_array,mysqli_error,mysqli_select_db,mysqli_connect

































Friday, February 15, 2013

Create a Database in MySQL

Create a Database in MySQL

 Creating  a Simple Database :

Syntax:
   Create Database [dbname]:

         Create Database HR;


Show Databases command Shows list of Databases Installed in the MySQL Server.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hr                 |
| joomla25102012     |
| magento            |
| mysql              |
| test               |
| wordpress          |
| zencart            |
+--------------------+
8 rows in set (0.01 sec)


Connect to Database/Connect to HR Database

mysql>use HR;

Database changed

Show all tables in the Database(HR)
 
mysql>Show Tables;
 
Empty set (0.00 sec)



Tags:Create Database in MySQL,
 Creating  a Simple Database in MySQL,List databases Installed in Mysql,Show databases Installed in Mysql, Connect to database, Show Tables in MySql,display Tables in Mysql,Display databases in MySQL,Create a Database in MySQL,Show all tables in the database

MySQL Data Types

MySQL Data Types

      MySQL  Data Types are used to store specific kind of data in the DataBase
 for ex: telephone number should be Numberic
            Name should be alphabets
            Date of Birth will be in Date Time Format etc.,


1)TINYINT
2)SMALLINT
3)MEDIUMINT
4)INT
5)BIGINT
6)FLOAT
7)DOUBLE
8)DECIMAL
9)BIT
10)CHAR
11)VARCHAR
12)TINYBLOB
13)TINYTEXT
14)BLOB
15)TEXT
16)MEDIUMBLOG
17)MEDIUMTEXT
18)LONGBLOB
19)LONGTEXT
20)ENUM
21)SET
22)DATE
23)TIME
24)DATETIME
25)YEAR
26)TIMESTAMP


Tags:  MYSQL Data Types,MySQL Datatypes, Data Types in MySQL, DataTypes in Mysql,MYSQL Date Datatypes, MySQL char DataTypes, MySQL Numeric Data Types

MATHEMATICAL Functions in MySQL

MATHEMATICAL Functions in MySQL


1) ABS
2)SIGN
3)MOD
4)FLOOR
5)CEIL
6)ROUND
7)EXP
8)LOG
9)LOG10
10)POW
11)POWER
12)SQRT
13)PI
14)COS
15)SIN
16)TAN
17)ACOS
18)ASIN
19)ATAN
20)ATAN2
21)COT
22)RAND
23)LEAST
24)GREATEST
25)DEGREES
26)RADIANS
27)TRUNCATE
28)BIN
29)OCT
30)HEX
31)CONV
32)COUNT
33)AVG
34)MIN
35)MAX
36)SUM
37)STD
38)STDDEV
39)BIT_OR
40)BIT_AND
 
Tags: Mathematical functions in MySQL, MySQL mathematical functions      

Thursday, February 14, 2013

Date and Time Functions in MySQL

Date and Time Functions in MySQL

MySQL Date and Time functions  are used to manipulate Date Columns in MySql Table,Views,Stored Procedures, & in Functions.

1)DAYOFWEEK
2)WEEKDAY
3)DAYOFMONTH
4)DAYOFYEAR
5)MONTH
6)DAYNAME
7)MONTHNAME
8)QUARTER
9)WEEK
10)YEAR
11)YEARWEEK
12)HOUR
13)MINUTE
14)SECOND
15)PERIOD_ADD
16)PERIOD_DIFF
17)DATE_ADD
18)DATE_SUB
19)ADDDATE
20)SUBDATE
21)TO_DAYS
22)FROM_DAYS
23)DATE_FORMAT
24)TIME_FORMAT
25)CURDATE
26)CURRENT_DATE
27)CURTIME
28)CURRENT_TIME
29)NOW
30)SYSDATE
31)CURRENT_TIMESTAMP
32)LOCATIME
33)LOCALTIMESTAMP
34)UNIX_TIMESTAMP
35)FROM_UNIXTIME
36)SEC_TO_TIME
37)TIME_TO_SEC

Tags: Date and Time Functions in MySQL, Date Functions in MySQL, Time Functions in MySQL,
MySQL date functions,MySQL Time Functions,MySQL Date and Time Functions.

String Functions in MySQL

String Functions in MySQL

MySQL String  functions are used to manipulate  String data type columns in MySQL Table,Stored Procedures,Views and in Functions.

1) ASCII
2)ORD
3)CHAR
4)CONCAT
5)CONCAT_WS
6)LENGTH
7)OCTET_LENGTH
8)CHAR_LENGTH
9)CHARACTER_LENGTH
10)BIT_LENGTH
11)LOCATE
12)POSITION
13)INSTR
14)LPAD
15)RPAD
16)LEFT
17)RIGHT
18)SUBSTRING
19) MID
20)SUBSTRING_INDEX
21)LTRIM
22)RTRIM
23)TRIM
24)SOUNDEX
25)SPACE
26)REPLACE
27)REPEAT
28)REVERSE
29)INSERT
30)ELT
31)FIELD
32)FIND_IN_SET
33)MAKE_SET
34)EXPORT_SET
35)LCASE
36)LOWER
37)UCASE
38)UPPER
39)LOAD_FILE
40)QUOTE


Tags:String Functions in MYSQL, String Manipulations in MYSQL

Thursday, February 7, 2013

PHP Convert String to an Array by length

PHP  Convert String to an Array by length


Split String by Length using str_split optionally pass Length(default value 1)
in PHP using str_split function user can split a string by length

Example 1:

Split a String by length 1

$input="Hello World! PHP Programmers!";
echo "<h4>Split by 1 char</h4>";
 print_r(str_split ( $input));

//OUTPUT:

Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => W [7] => o [8] => r [9] => l [10] => d [11] => ! [12] => [13] => P [14] => H [15] => P [16] => [17] => P [18] => r [19] => o [20] => g [21] => r [22] => a [23] => m [24] => m [25] => e [26] => r [27] => s [28] => ! )

Example 2:

Split a String by length2
$input="Hello World! PHP Programmers!";

 echo "<h4>Split by 2 char</h4>";
 print_r(str_split ( $input,2));
 
//OUTPUT:
Array ( [0] => He [1] => ll [2] => o [3] => Wo [4] => rl [5] => d! [6] => P [7] => HP [8] => P [9] => ro [10] => gr [11] => am [12] => me [13] => rs [14] => ! ) 
 Split a String by length 5

Example 3:

$input="Hello World! PHP Programmers!";


  echo "<h4>Split by 5 char</h4>";
 print_r(str_split ( $input,5));
//OUTPUT:

Array ( [0] => Hello [1] => Worl [2] => d! PH [3] => P Pro [4] => gramm [5] => ers! ) 


Tags: Split a String by Length, Convert String to an Array in PHP,str_split in php, make string as an array,print array in php using print_r

Thumbnail Images using Gmagick

Thumbnail Images in PHP


using GMagic

Installing  Gmagick in Windows.

Download Thread-safe Gmagic dll


PHP XMLWriter

PHP XMLWriter

    This example demonstrates How to generate XML content in memory using XMLWriter object.


Step 1) Create XMLWriter object

   $writer =  new XmlWriter();

Step 2)  Open in Memory Connection and assign it to XmlWriter

$writer->openMemory();

Step 3) Create Document Declaration/Xml Processing Instruction

$writer->startDocument("1.0","utf-8");

Step 4)   Optional filed Set Indentation

$writer->setIndent(true);

Step 5)  Write  Start Element/root element in this xml.

$writer->startElement("bookslist");

Step 6) Write remaining elements under root element(step 5).

book node has title,price,publisher and authors list.  

Each node has start element & end element.
if node has data  use text method to write content to that element.

$writer->startElement("book");
$writer->startAttribute("id"); //writing id attribute to book's node.
$writer->text("ISBN-978-3-16-148410-0");
$writer->endAttribute();
$writer->startElement("title"); //start element name title
$writer->text("PHP programming");//write text to that title
$writer->endElement(); //end the title element.
//repeates above process for remaining elements.

$writer->startElement("Price");
$writer->text("$33.39");
$writer->endElement();

$writer->startElement("publisher");
$writer->text("Sams");
$writer->endElement();
//book has 1 or more authors in that case
//authors root node has author sub node which has firstname and lastname,
//you can add as many author nodes to authors node.
//here we have 1 author.
$writer->startElement("authors");
$writer->startElement("author");
$writer->startElement("firstname");
$writer->text("jhon");
$writer->endElement();
$writer->startElement("lastname");
$writer->text("solomon");
$writer->endElement();
$writer->endElement();

$writer->endElement();

Step 7)  Close StartElement tag here
$writer->endElement();

Step 8)  Close Document

$writer->endDocument();

Step 9)  See output.

echo $writer->outputMemory()."<br>";


Step 10) Here is the output.(if u see only content in the browser then context menu has View Page Source )

OUTPUT

<bookslist>
 <book id="ISBN-978-3-16-148410-0">
  <title>PHP programming</title>
  <Price>$33.39</Price>
  <publisher>Sams</publisher>
  <authors>
   <author>
    <firstname>jhon</firstname>
    <lastname>solomon</lastname>
   </author>
  </authors>
 </book>
</bookslist>

Tags:PHP XmlWriter,XMLWriter::setInden,XMLWriter::startDocument,
XMLWriter::endDocument,XmlWriter::startElement,XmlWriter::EndElement,XMLWriter::text,
XMLWriter::outputMemory,XMLWriter::openMemory, Writing XML content in PHP,Generating XML content in PHP.

Wednesday, February 6, 2013

time in PHP

time in PHP

time function returns number of seconds last since  01-01-1970 12:00 AM.

echo time();

for ex: 

1360221790  //output


Get Today's date and time in PHP.

echo "<h2>display Current date and time using date object</h2>";
echo date("D/j/Y h:i:s a",time());

//OUTPUT:Thu/7/2013 02:23:10 am


  • GET ATOM Date and time format
 
echo "<h3> ATOM Date format</h3>";
echo date(DATE_ATOM,time());
 
OUTPUT:

ATOM Date format

2013-02-07T02:23:10-05:00

  • Get RSS Date and Time format

echo "<h3> RSS Date format</h3>";
echo date(DATE_RSS,time());
 
//OUTPUT:

RSS Date format

Thu, 07 Feb 2013 02:23:10 -0500

  • Get COOKIE Date and Time Format:

echo "<h3> COOKIE Date format</h3>";
echo date(DATE_COOKIE,time());
 
//OUTPUT:

COOKIE Date format

Thursday, 07-Feb-13 02:23:10 EST

  • Get W3C date and Time format

echo "<h3> W3C Date format</h3>";
echo date(DATE_W3C,time());
 
//OUTPUT:

W3C Date format

2013-02-07T02:23:10-05:00



Complete Source Code

<?php

 date_default_timezone_set("America/New_York");
echo "<h1> time() function in PHP</h1>";
echo "<h1>PHP gives current time in seconds since 1970 january 1 12:00AM to current time<h1>";
echo time();


echo "<h2>display Current date and time using date object</h2>";

echo date("D/j/Y h:i:s a",time());

echo "<h3> ATOM Date format</h3>";
echo date(DATE_ATOM,time());

echo "<h3> COOKIE Date format</h3>";
echo date(DATE_COOKIE,time());

echo "<h3> RSS Date format</h3>";
echo date(DATE_RSS,time());

echo "<h3> W3C Date format</h3>";
echo date(DATE_W3C,time());
?>

 

Note:  You need to set   date_default_timezone_set("America/New_York");
to existing values supported by PHP  refer   otherwise warning message will be displayed:

"Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. " 

tags: time in php, get current date and time in PHP, get today's date in PHP, get Current date and time using PHP time, Get RSS date format in PHP,
Get ATOM date format in PHP,Get W3C date format in PHP,
Get COOKIE date format in PHP.DateTime formats in PHP. time() function in PHP

PUSH POP in PHP Arrays

PUSH POP in PHP Arrays

Creating dynamic arrays in PHP using PUSH POP methods.


syntax:   arraycount=array_push(arrayname,value);


//Create dymmy array
$dynArr = array(); 

//keep on add elements to an array.

echo "count=".array_push($dynArr,"Hello");
echo "count=".array_push($dynArr,"World!");
echo "count=".array_push($dynArr,"PHP");
echo "count=".array_push($dynArr,"Programmers");

//OUTPUT:
count=1count=2count=3count=4

 Array has 4 elements


Here we have 2 choices.  
                  1.Using foreach/for statement to loop through array elements.
                  2. using Array_pop : fetches elements in reverse order of  insertion.
                 

Once you pop array elements ,count will be decreased automatically.

Method1

Print array elements

print_r($dynArr);


Method 2:

using array_pop:

$count = count($dynArr);
for($i=0; $i < $count; $i++)
{
  echo "Array count=".count($dynArr)."&nbsp;&nbsp;";
  echo "Array element=".array_pop($dynArr)."<br>";
}

//OUTPUT

Array count=4  Array element=Programmers
Array count=3  Array element=PHP
Array count=2  Array element=World!
Array count=1  Array element=Hello

 

Complete Source Code:

 <?php

echo "<h1>Dynamic Arrays in PHP</h1>";

$dynArr = array();
echo "count=".array_push($dynArr,"Hello");
echo "count=".array_push($dynArr,"World!");
echo "count=".array_push($dynArr,"PHP");
echo "count=".array_push($dynArr,"Programmers");


echo "<h2> Display all Array elements</h2>";

print_r($dynArr);

echo "<h2> POP ALL ARRAY ELEMENTS</h2>";

//echo "Array element".array_pop($dynArr);

foreach($dynArr as $index=>$value)
{
echo "index",$index,"Value",$value."<br/>";
}

$count = count($dynArr);
for($i=0; $i < $count; $i++)
{
   echo "Array count=".count($dynArr)."&nbsp;&nbsp;";
  echo "Array element=".array_pop($dynArr)."<br>";

}
?>


Tags:

push pop in php arrays,

Array_pop in PHP,Array_push in PHP, Dynamic Arrays in PHP, Array count in PHP,foreach in PHP,

array_sum in PHP

array_sum in PHP

   array_sum calculates sum of values in an array.

Syntax:   sumoutput= array_sum(inputArray);
      

//Integer sum Array

$intArr = array(1,2,34,4,5,6);
echo "Array Sum=",array_sum($intArr);
 
//Output:  52

//Float/Decimal Array Sum

 
$fArr = array(1.1,2.22,34.44,4.55,5.3,6.3);
echo "Array Sum=",array_sum($fArr);
 
//output:53.19

$fArr = array(0.1,.2,.34,.4,.5,.6);
echo "Array Sum=",array_sum($fArr);
 
//output: 2.14
 
         

complete source code

<?php
echo "<h1> PHP array_sum  </h1>";

$intArr = array(1,2,34,4,5,6);
echo "Array Sum=",array_sum($intArr);

$fArr = array(1.1,2.22,34.44,4.55,5.3,6.3);
echo "Array Sum=",array_sum($fArr);

$fArr = array(0.1,.2,.34,.4,.5,.6);
echo "Array Sum=",array_sum($fArr);

?>


Tags: PHP array_sum,calculate array sum in php using arra_sum,Integeter Arrays sum in PHP,Float Arrays sum in php,decimal Arrays Sum in PHP,PHP 5.3.2

PHP Explode tutorial

PHP Explode tutorial

Syntax:

$array=explode(delimter,inputString);

Splits  input string into an Array. or Converts a input String into an Array using explode function.

Example 1

$inputString= "Hello world this is PHP programmers conference!";

//Here delimiter space ' '
$strArr = explode(' ',$inputString);

print_r($strArr);




Example 2

echo "<br>Example 2<br>";
$str = "1,2,3,4,5,6";
$strArr = explode(' ',$str);
print_r($strArr);


//output  


Array ( [0] => 1,2,3,4,5,6 ) 

 

Example 3

 

echo "<br>Example 2<br>";
$str = "1,2,3,4,5,6";
$strArr = explode(',',$str);
print_r($strArr);

echo "<br>";
echo "Array Sum=".array_sum($strArr);

//output

array_sum:21

PHP Explode tutorial


Tags:PHP Explode tutorial, split input string to an array, convert string to an array,explode input string to an array,converts an input string into an array,php explode,php 5.3.2

Friday, February 1, 2013

PHP Arrays Tutorial

PHP Arrays Tutorial

    PHP Arrays are one type of Data Structure to Store Multiple values under single name. These values can be randomly accessed.  

PHP Provides built-in functions to sort,search,remove array elements.


How to Create Numeric Indexed Arrays in PHP

$intarr = array(1,2,3,4,5,6);

Here array name is : $intarr
It has 6 elements .

Find Length of the Array Programmatically

$arrCount = count($intarr);  //output : 6
echo "Array length:",$arrCount; 


$arrCount = sizeof($intarr);  //output : 6
echo "Array length:",$arrCount; 


*sizeof is an alias name for count function

Display Array Elements using for loop

for($i=0; $i < count($intarr); $i++)
{
echo "Value at ",$i," is ",$intarr[$i],"<br/>";
}



Display Array Elements using foeach statement

foreach($intarr as $i=>$value)

{
echo "Value at ",$i," is ",$value,"<br/>";
}
 

Associate Arrays in PHP 

  First section creates arrays with numeric indexed values.  PHP allows us to give meaningful names to  indexes.

Here is an Example.
$AddressArray = array("name"=>"Same benegal","city"=>"Hyderabad","ZIP"=>"94086","country"=>"USA");

array has 3 elements each indexed with name,city,zip,country.

How to access array elements using foreach statement

foreach($AddressArray as $i=>$value)
{
    echo "Value at <b>",$i,"</b> is <i>",$value,"</i><br/>";
}

*Foreach statement, is most useful in associate arrays in php

OUTPUT

Arrays in PHP

Integer Indexed Arrays in PHP
Value at 0 is 1
Value at 1 is 2
Value at 2 is 3
Value at 3 is 4
Value at 4 is 5
Value at 5 is 6
loop through using foreach statement
Value at 0 is 1
Value at 1 is 2
Value at 2 is 3
Value at 3 is 4
Value at 4 is 5
Value at 5 is 6

Associate Arrays in php

loop through using foreach statement
Value at name is Same benegal
Value at city is Hyderabad
Value at ZIP is 94086
Value at country is USA


Complete Source Code


<?php

$intarr = array(1,2,3,4,5,6);
echo "<h1>Arrays in PHP</h1>";
echo "<h6>Integer Indexed Arrays in PHP</h6>";
for($i=0; $i < sizeof($intarr); $i++)
{
echo "Value at ",$i," is ",$intarr[$i],"<br/>";
}
echo "<b>loop through using foreach statement</b><br/>";
foreach($intarr as $i=>$value)

{
echo "Value at ",$i," is ",$value,"<br/>";
}

echo "<h1> Associate Arrays in php </h1>";
$StringArray = array("name"=>"Same benegal","city"=>"Hyderabad","ZIP"=>"94086","country"=>"USA");
echo "<b>loop through using foreach statement</b><br/>";
foreach($StringArray as $i=>$value)
{

    echo "Value at <b>",$i,"</b> is <i>",$value,"</i><br/>";


}
?>


Tags:PHP Arrays,PHP Arrays Tutorial,PHP Numeric indexed arrays,PHP associate Arrays, PHP foreach Statement, PHP for loop, PHP Array size,PHP Array Count,PHP count function,PHP sizeof function.How to Create PHP arrays, How to create associate arrays in PHP,How to access array elements in PHP,PHP arrays source code.