PHP

Array, String, Date &Time function

Posted on Updated on

Arrays

An array stores multiple values in one single variable:

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

Example

<?php
$cars=array(“Volvo”,”BMW”,”Toyota”);
echo “I like ” . $cars[0] . “, ” . $cars[1] . ” and ” . $cars[2] . “.”;
?>

O/P: I like Volvo, BMW and Toyota.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

  • Numeric array – An array with a numeric index. Values are stored and accessed in linear fashion
  • Associative array – An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array – An array containing one or more arrays and values are accessed using multiple indices

Numeric Array

These arrays can store numbers, strings and any object but their index will be prepresented by numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.

<html>

<body>

<?php

/* First method to create array. */

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

foreach( $numbers as $value )

{

echo “Value is $value <br />”;

}

/* Second method to create array. */

$numbers[0] = “one”;

$numbers[1] = “two”;

$numbers[2] = “three”;

$numbers[3] = “four”;

$numbers[4] = “five”;

foreach( $numbers as $value )

{

echo “Value is $value <br />”;

}

?>

</body>

</html>

This will produce following result:

Value is 1Value is 2Value is 3Value is 4Value is 5Value is oneValue is twoValue is threeValue is fourValue is five

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

NOTE: Don’t keep associative array inside double quote while printing otheriwse it would not return any value.

Example

1

This will produce following result:

2

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three subjects:

This example is an associative array, you can create numeric array in the same fashion.

3

This will produce following result:

4

String Concatenation Operator

To concatenate two string variables together, use the dot (.) operator:

5

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.

Using the strlen() function

The strlen() function is used to find the length of a string.

Let’s find the length of our string “Hello world!”:

<?php

echo strlen(“Hello world!”);

?>

This will produce following result:

12

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.

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(“Hello world!”,”world”);

?>

This will produce following result:

6

As you see the position of the string “world” in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.

Date and Time

The PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and time.

Syntax

date(format,timestamp)

Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time

A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.

Get a Simple Date

The required format parameter of the date() function specifies how to format the date (or time).

Here are some characters that are commonly used for dates:

  • d – Represents the day of the month (01 to 31)
  • m – Represents a month (01 to 12)
  • Y – Represents a year (in four digits)
  • l (lowercase ‘L’) – Represents the day of the week

Other characters, like”/”, “.”, or “-” can also be inserted between the characters to add additional formatting.

The example below formats today’s date in three different ways:

Example

<?php
echo “Today is ” . date(“Y/m/d”) . “<br>”;
echo “Today is ” . date(“Y.m.d”) . “<br>”;
echo “Today is ” . date(“Y-m-d”) . “<br>”;
echo “Today is ” . date(“l”);
?>

O/P:

Today is 2014/08/23
Today is 2014.08.23
Today is 2014-08-23
Today is Saturday

Get a Simple Time

Here are some characters that is commonly used for times:

  • h – 12-hour format of an hour with leading zeros (01 to 12)
  • i – Minutes with leading zeros (00 to 59)
  • s – Seconds with leading zeros (00 to 59)
  • a – Lowercase Ante meridiem and Post meridiem (am or pm)

The example below outputs the current time in the specified format:

Example

<?php
echo “The time is ” . date(“h:i:sa”);
?>

O/P: The time is 05:42:07am

Posted By-: Vissicomp Technology Pvt. Ltd.

Website -: http://www.vissicomp.com

Php, Php Variable, Php Constant

Posted on

What is PHP?

  • PHP is an acronym for “PHP Hypertext Preprocessor”.
  • PHP is a widely-used, open source scripting language.
  • PHP scripts are executed on the server.
  • PHP costs nothing, it is free to download and use.

What is a PHP File?

  • PHP files can contain text, HTML, CSS, JavaScript, and PHP code
  • PHP code are executed on the server, and the result is returned to the browser as plain HTML
  • PHP files have extension “.php”

What Can PHP Do?

  • PHP can generate dynamic page content
  • PHP can create, open, read, write, delete, and close files on the server
  • PHP can collect form data
  • PHP can send and receive cookies
  • PHP can add, delete, modify data in your database
  • PHP can restrict users to access some pages on your website
  • PHP can encrypt data

Why PHP?

  • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP supports a wide range of databases
  • PHP is free. Download it from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side

What Do I Need?

To start using PHP, you can:

  • Find a web host with PHP and MySQL support
  • Install a web server on your own PC, and then install PHP and MySQL

Basic PHP Syntax

  • A PHP script can be placed anywhere in the document.
  • A PHP script starts with <?php and ends with ?>:
  • <?php
    // PHP code goes here
    ?>

PHP Variables

As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

Rules for PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case sensitive ($y and $Y are two different variables)

NOTE:  Remember that PHP variable names are case-sensitive!

Creating (Declaring) PHP Variables

PHP has no command for declaring a variable.

A variable is created the moment you first assign a value to it:

Example

<?php
$txt=”Hello world!”;
$x=5;
$y=10.5;
?>

5

After the execution of the statements above, the variable txt will hold the value Hello world!, the variable x will hold the value 5, and the variable y will hold the value 10.5.

Note: When you assign a text value to a variable, put quotes around the value.

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically converts the variable to the correct data type, depending on its value.

In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.

PHP Variables Scope

In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

  • local
  • global
  • static

Example

<?php
$x=5; // global scope

function myTest() {
$y=10; // local scope
echo “<p>Test variables inside the function:</p>”;
echo “Variable x is: $x”;
echo “<br>”;
echo “Variable y is: $y”;
}
myTest();
echo “<p>Test variables outside the function:</p>”;
echo “Variable x is: $x”;
echo “<br>”;
echo “Variable y is: $y”;
?>

In the example above there are two variables $x and $y and a function myTest(). $x is a global variable since it is declared outside the function and $y is a local variable since it is created inside the function.

When we output the values of the two variables inside the myTest() function, it prints the value of $y as it is the locally declared, but cannot print the value of $x since it is created outside the function.

Then, when we output the values of the two variables outside the myTest() function, it prints the value of $x, but cannot print the value of $y since it is a local variable and it is created inside the myTest() function.

NOTE: You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:

Example

<?php
function myTest() {
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>

1

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

Note: The variable is still local to the function.

PHP Constants

A constant is an identifier (name) for a simple value. The value cannot be changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Note: Unlike variables, constants are automatically global across the entire script.

Set a PHP Constant

To set a constant, use the define() function – it takes three parameters: The first parameter defines the name of the constant, the second parameter defines the value of the constant, and the optional third parameter specifies whether the constant name should be case-insensitive. Default is false.

Example

<?php
define(“GREETING”, “Welcome to W3Schools.com!”, true);
echo greeting;
?>

Posted By-: Vissicomp Technology Pvt. Ltd.

Website -: http://www.vissicomp.com

Simple PHP

Posted on Updated on

<html><head><title>A Simple PHP page that accepts user information</title></head>

<body>

<div>

<?php

print “Welcome “.$_GET[‘user’].”<br>”;

print “You came from “.$_GET[‘address’].”<br>”;

?></div>

</body>

</html>

program in to php accepts user information
program in to php accepts user information

Form in PHP

Posted on Updated on

<html><head>

                                <title>A Simple HTML page to provide information for PHP</title></head>

                                <body>

                                <div>

                <form action = “pp1.php” method = “get”>

                <p>User Name : <input type = “text” name = “user”></p>

                <p>Address : <textarea name = “address” rows = “3” cols=”30″></textarea></p>

                <p><input type = “submit” value = “Send”></p>

                </form></div>

                </body>

                </html>

Form_php1
Form_php1