0% found this document useful (0 votes)
19 views13 pages

I PHP Unit2 Degree

The document discusses different types of arrays in PHP including numeric, associative, and multidimensional arrays. It also covers creating and manipulating arrays using functions like count(), foreach(), reset(), array_push(), array_pop(), array_unshift(), array_shift(), and array_merge().

Uploaded by

yijani2341
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views13 pages

I PHP Unit2 Degree

The document discusses different types of arrays in PHP including numeric, associative, and multidimensional arrays. It also covers creating and manipulating arrays using functions like count(), foreach(), reset(), array_push(), array_pop(), array_unshift(), array_shift(), and array_merge().

Uploaded by

yijani2341
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Srinivasa Degree College PHP and My SQL

UNIT II
TOPIC 1:
Arrays
arrays are special types of variables that enable you to store as many values. Arrays are indexed,
which means that each entry is made up of a key and a value.
• The key is the index position, beginning with 0 and increasing incrementally by 1 with each new
element in the array.
• The value is whatever value you associate with that position—a string, an integer, or whatever you
want.
Creating Arrays
You can create an array using either the array() function or the array operator []. The array() function
is usually used when you want to create a new array with more than one element. The array operator is
often used when you want to create a new array with just one element at the outset, or when you want to
add to an existing array element. The following code shows how to create an array
$rainbow = array(“red”, “orange”, “yellow”, “green”, “blue”, “indigo”, “violet”);
The following shows the same array being created incrementally using the array operator ([]):
$rainbow[] = “red”;
$rainbow[] = “orange”;
$rainbow[] = “yellow”;
$rainbow[] = “green”;
$rainbow[] = “blue”;
$rainbow[] = “indigo”;
$rainbow[] = “violet”;
Both examples create a seven-element array called $rainbow, with values starting at index position 0 and
ending at index position 6.
$rainbow[0] = “red”;
$rainbow[1] = “orange”;
$rainbow[2] = “yellow”;
$rainbow[3] = “green”;
$rainbow[4] = “blue”;
$rainbow[5] = “indigo”;
$rainbow[6] = “violet”;
you initially create your array using the array() function or the array operator, you can still add to it
using the array operator. In the first line of the following example, six elements are added to the array, and
one more element is added to the end of the array in the second line:
EX: $rainbow = array(“red”, “orange”, “yellow”, “green”, “blue”, “indigo”);
$rainbow[] = “violet”;
TOPIC 2:
Types of Arrays:
There are three different kind of arrays and each array value is accessed using array index.
• Numeric array
• Associative array
• Multidimensional array
Numeric array
An array with a numeric index. Values are stored and accessed in linear fashion.
You can create an numeric array using either the array() function or the array operator []. The array() function
is usually used when you want to create a new array with more than one element. The array operator is
often used when you want to create a new array with just one element at the outset, or when you want to
add to an existing array element. The following code shows how to create an array
III BCom- SEMVI UNIT II Page 1
Srinivasa Degree College PHP and My SQL
$rainbow = array(“red”, “orange”, “yellow”, “green”, “blue”, “indigo”, “violet”);
The following shows the same array being created incrementally using the array operator ([]):
$rainbow[] = “red”;
$rainbow[] = “orange”;
$rainbow[] = “yellow”;
$rainbow[] = “green”;
$rainbow[] = “blue”;
$rainbow[] = “indigo”;
$rainbow[] = “violet”;
Both examples create a seven-element array called $rainbow, with values starting at index position 0 and
ending at index position 6.
$rainbow[0] = “red”;
$rainbow[1] = “orange”;
$rainbow[2] = “yellow”;
$rainbow[3] = “green”;
$rainbow[4] = “blue”;
$rainbow[5] = “indigo”;
$rainbow[6] = “violet”;
you initially create your array using the array() function or the array operator, you can still add to it
using the array operator. In the first line of the following example, six elements are added to the array, and
one more element is added to the end of the array in the second line:
EX: $rainbow = array(“red”, “orange”, “yellow”, “green”, “blue”, “indigo”);
$rainbow[] = “violet”;
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.
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.
The following example demonstrates this by creating an array called $character with four elements:
$character = array(“name” => “Bob”,
“occupation” => “superhero”,
“age” => 30,
“special power” => “x-ray vision”);
The four keys in the $character array are name, occupation, age, and special power. The associated
values are Bob, superhero, 30, and x-ray vision, respectively. You can reference specific elements of an
associative array using the specific key, such as in this example:
echo $character[‘occupation’];
The output:
superhero
As with numerically indexed arrays, you can use the array operator to add to an associative array:
$character[‘supername’] = “Mega X-Ray Guy”;
This example adds a key called supername with a value of Mega X-Ray Guy. The only difference
between an associative array and a numerically indexed array is the key name. In a numerically indexed
array, the key name is a number. In an associative array, the key name is a meaningful word.
Multidimensional array -
An array containing one or more arrays and values are accessed using multiple indices. 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.

III BCom- SEMVI UNIT II Page 2


Srinivasa Degree College PHP and My SQL
<?php
$characters = array(
array( “name” => “Bob”,
“occupation” => “superhero”,
“age” => 30,
“special power” => “x-ray vision”),
array(“name” => “Sally”,
“occupation” => “superhero”,
“age” => 24,
“special power” => “superhuman strength”),
array(“name” => “Jane”,
“occupation” => “arch villain”,
“age” => 45,
“special power” => “nanotechnology”)
);
?>
In line 2, the $characters array is initialized using the array() function. Lines 3–8 represent the first
element, lines 9–14 represent the second element, and lines 15–20 represent the third element. These
elements can be referenced as $characters[0], $characters[1], and $characters[2].
Each element consists of an associative array, itself containing four elements: name, occupation, age,
and special_power.
However, if you attempt to print the master elements like so
echo $characters[1];
the output will be
Array
Because the master element indeed holds an array as its content. To really get to the content you
want (that is, the specific information found within the inner array element), you need to access the master
element index position plus the associative name of the value you want to view.
example:
echo $characters[1][‘occupation’];
It prints this:
superhero
TOPIC 3:
Array-Related Constructs and Functions
count() and sizeof()—Each of these functions counts the number of elements in an array. Given the
following array
$colors = array(“blue”, “black”, “red”, “green”);
both count($colors); and sizeof($colors); return a value of 4.
foreach()—This control structure is used to step through an array, assigning the value of an element to a
given variable, as you saw in the previous section.
reset()—This function rewinds the pointer to the beginning of an array, as in this example:
reset($character);
This function proves useful when you are performing multiple manipulations on an array, such as sorting,
extracting values, and so forth.
array_push()—This function adds one or more elements to the end of an existing array, as in this example:
array_push($existingArray, “element 1”, “element 2”, “element 3”);
array_pop()—This function removes (and returns) the last element of an existing array, as in this example:
$last_element = array_pop($existingArray);
array_unshift()—This function adds one or more elements to the beginning of an existing array, as in this
example:
III BCom- SEMVI UNIT II Page 3
Srinivasa Degree College PHP and My SQL
array_unshift($existingArray, “element 1”, “element 2”, “element 3”);
array_shift()—This function removes (and returns) the first element of an existing array, as in this example,
where the value of the element in the first position of $existingArray is assigned to the variable
$first_element:
$first_element = array_shift($existingArray);
array_merge()—This function combines two or more existing arrays, as in this example:
$newArray = array_merge($array1, $array2);
array_keys()—This function returns an array containing all the key names within a given array, as in this
example:
$keysArray = array_keys($existingArray);
array_values()—This function returns an array containing all the values within a given array, as in this
example:
$valuesArray = array_values($existingArray);
TOPIC 4:
Formatting Strings with PHP
PHP provides two functions that enable you first to apply formatting, whether to round doubles to a
given number of decimal places, define alignment within a field, or display data according to different
number systems.
In this section, you learn a few of the formatting options provided by printf() and sprintf().
Working with printf()
The printf() function requires a string argument, known as a format control string. It also accepts
additional arguments of different types. The format control string contains instructions regarding the display
of these additional arguments. The following fragment, for example, uses printf() to output an integer as an
octal (or base-8) number:
<?php
printf(“This is my number: %o”, 55); // prints “This is my number: 67”
?>
The format control string (the first argument) is a special code, known as a conversion specification.
A conversion specification begins with a percent (%) symbol and defines how to treat the corresponding
argument to printf(). You can include as many conversion specifications as you want within the format
control string, as long as you send an equivalent number of arguments to printf().
The following fragment outputs two floating-point numbers using printf():
<?php
printf(“First number: %f<br/>Second number: %f<br/>”, 55, 66);
// Prints:
// First number: 55.000000
// Second number: 66.000000
?>
The first conversion specification corresponds to the first of the additional arguments to printf(), or
55. The second conversion specification corresponds to 66. The f following the percent symbol requires that
the data be treated as a floating-point number.
Type Specifiers
The part of the conversion specification is the type specifier. You have already come across two type
specifiers, o, which displays integers as octals, and f, which displays integers as floating-point numbers. Table
10.1 lists the other type specifiers available.

III BCom- SEMVI UNIT II Page 4


Srinivasa Degree College PHP and My SQL

Demonstrating Some Type Specifiers


1: <?php
2: $number = 543;
3: printf(“Decimal: %d<br/>”, $number);
4: printf(“Binary: %b<br/>”, $number);
5: printf(“Double: %f<br/>”, $number);
6: printf(“Octal: %o<br/>”, $number);
7: printf(“String: %s<br/>”, $number);
8: printf(“Hex (lower): %x<br/>”, $number);
9: printf(“Hex (upper): %X<br/>”, $number);
10: ?>
Padding Output with a Padding Specifier
You can require that output be padded by leading characters. The padding specifier should directly
follow the percent sign that begins a conversion specification. To pad output with leading zeros, the padding
specifier should consist of a zero followed by the number of characters you want the output to take up. If
the output occupies fewer characters than this total, zeros fill the difference:
<?php
printf(“%04d”, 36); // prints “0036”
?>
To pad output with leading spaces, the padding specifier should consist of a space character followed
by the number of characters that the output should occupy:
<?php
printf(“% 4d”, 36) // prints “ 36”
?>
You can specify any character other than a space or a zero in your padding specifier
with a single quotation mark followed by the character you want to use:
<?php
printf (“%’x4d”, 36); // prints “xx36”
?>
Specifying a Field Width
You can specify the number of spaces within which your output should sit. A field width specifier is
an integer that should be placed after the percent sign that begins a conversion. The following fragment
outputs a list of four items, all of which sit within a field of 20 spaces. To make the spaces visible on the
browser, place all the output within a pre element:
<?php
printf(“%20s\n”, “Books”);
printf(“%20s\n”, “CDs”);

III BCom- SEMVI UNIT II Page 5


Srinivasa Degree College PHP and My SQL
printf(“%20s\n”, “DVDs”);
printf(“%20s\n”, “Games”);
printf(“%20s\n”, “Magazines”);
?>

Specifying Precision
If you want to output data in floating-point format, you can specify the precision to which you want
to round your data. This proves particularly useful when dealing with currency. The precision identifier
should be placed directly before the type specifier. It consists of a dot followed by the number of decimal
places to which you want to round. This specifier has an effect only on data that is output with the f type
specifier:
<?php
printf(“%.2f”, 5.333333); // prints “5.33”
?>
Conversion Specifications:

Storing a Formatted String


The printf() function outputs data to the browser. The function sprintf(), which is used just like printf()
except that it returns a string that can be stored in a variable for later use. The following fragment uses
sprintf() to round a double to two decimal places, storing the result in $cash:
<?php
$cash = sprintf(“%.2f”, 21.334454);
echo “You have \$$cash to spend.”; // Prints “You have $21.33 to spend.”
?>
TOPIC 5:
Investigating Strings in PHP:
Strings can arrive from many sources, including user input, databases, files, and web pages. Before
you begin to work with data from an external source, you often need to find out more about the data. PHP
provides many functions that enable you to acquire information about strings.

III BCom- SEMVI UNIT II Page 6


Srinivasa Degree College PHP and My SQL
About Indexing Strings
A string as an array of characters, and thus you can access the individual characters of a string as if
they were elements of an array:
<?php
$test = “phpcoder”;
echo $test[0]; // prints “p”
echo $test[4]; // prints “o”
?>
Finding the Length of a String with strlen()
You can use the built-in strlen() function to determine the length of a string. This function requires a
string as its argument and returns an integer representing the number of characters in the string you passed
to it.
EX:
<?php
$membership = “pAB7”;
echo $membership:
?>
It returns 4.
Finding a Substring Within a String with strstr()
The strstr() function is test whether a string exists within another string. This function requires two
arguments: the source string and the substring you want to find within it. The function returns false if it
cannot find the substring; otherwise, it returns the portion of the source string, beginning with the substring.
EX:
<?php
$m = “pAB7”;
echo strstr($m,"AB");
?>
The strstr() function returns the string AB7.
Finding the Position of a Substring with strpos()
The strpos() function tells you whether a string exists within a larger string as well as where it is found.
The strpos() function requires two arguments: the source string and the substring. The function also accepts
an optional third argument, an integer representing the index from which you want to start searching.
If the substring does not exist, strpos() returns false; otherwise, it returns the index at which the
substring begins.
EX:
<?php
$m= “mz00xyz”;
echo strpos($m, "mz”;
?>
The strpos() function finds mz in the string, it finds it at the first element—the 0 position.
Extracting Part of a String with substr()
The substr() function returns a string, based on the start index and length of the characters. This
function requires two arguments: a source string and the starting index. Using these arguments, the function
returns all the characters from the starting index to the end of the string you are searching. You can also
provide a third argument—an integer representing the length of the string you want returned. If this third
argument is present, substr() returns only that number of characters, from the start index onward:
<?php
$test = “phpcoder”;
echo substr($test,3).”<br/>”; // prints “coder”

III BCom- SEMVI UNIT II Page 7


Srinivasa Degree College PHP and My SQL
echo substr($test,3,2).”<br/>”; // prints “co”
?>
TOPIC 6:
Manipulating Strings with PHP
PHP provides different string manipulation functions.
trim():
The trim() function removes any whitespace characters, including newlines, tabs, and spaces, from both the
start and end of a string. It accepts the string to modify, returning the cleaned-up version. For example:
<?php
$text = “\t\tlots of room to breathe\t “;
echo “$text”;
?>
It prints “ lots of room to breathe “
rtrim()
The rtrim() function keep whitespace at the beginning of a string but remove it from the end. That
means the rtrim() function removes whitespace at only the end of the string :
<?php
$text = “\t\tlots of room to breathe \t“;
echo “$text”;
?>
It prints “ lots of room to breathe “;
ltrim()
The ltrim() function keep whitespace at the ending of a string but remove it from the beginning. That means
the ltrim() function removes whitespace at only the beginning of the string :
<?php
$text = “\t\tlots of room to breathe\t “;
echo “$text”;
?>
It prints “ lots of room to breathe “
strip_tags()
this function used to remove tags from a block of text to display it without any HTML formatting.
The strip_tags() function accepts two arguments: the text to transform and an optional set of HTML tags
that strip_tags() can leave in place.
<?php
$string = “<b><u>hi<br>hello</b></u>”; //it returns hi
hello
echo strip_tags($string, “<b>”);
?>
after strip_tags() It returns hi hello
Replacing a Portion of a String Using substr_replace()
The substr_replace() function works similarly to the substr() function, except it enables you to replace
the portion of the string that you extract. The function requires three arguments: the string to transform,
the text to add to it, and the starting index; it also accepts an optional length argument. The substr_replace()
function finds the portion of a string specified by the starting index and length arguments, replaces this
portion with the string provided, and returns the entire transformed string.
<?php
$m = “mz11xyz”;
$m1 = substr_replace($m, “12”, 2, 2);
echo "$m1”;

III BCom- SEMVI UNIT II Page 8


Srinivasa Degree College PHP and My SQL
?>
The result of this code is that “mz12xyz”.
Replacing Substrings Using str_replace
The str_replace() function is used to replace all instances of a given string within another string. It
requires three arguments: the search string, the replacement string, and the master string. The function
returns the transformed string.
<?php
$string = “welcome 2010”;
echo str_replace(“2010”,”2012”,$string);
?>
It returns welcome 2012
Converting Case
PHP provides several functions that allow you to convert the case of a string. Changing case is often
useful for string comparisons.
strtoupper():
To get an uppercase version of a string, use the strtoupper() function. This function requires only the
string that you want to convert and returns the converted string:
<?php
$membership = “mz11xyz”;
echo strtoupper($membership); // prints “MZ11XYZ”
?>
strtolower()
To convert a string to lowercase characters, use the strtolower() function. Once again, this function
requires the string you want to convert and returns the converted version:
<?php
$membership = “MZ11XYZ”;
echo strtolower($membership); // prints “mz11xyz”
?>
ucwords()
The ucwords() function makes the first letter of every word in a string uppercase. The following
fragment makes the first letter of every word in a user-submitted string uppercase:
<?php
$full_name = “violet elizabeth bott”;
echo ucwords($full_name); // prints “Violet Elizabeth Bott”
?>
ucfirst()
The ucfirst() function capitalizes only the first letter in a string. The following fragment capitalizes the
first letter in a user-submitted string:
<?php
$myString = “this is my string.”;
echo ucfirst($myString);// prints “This is my string.”
?>
Wrapping Text with wordwrap() and nl2br():
nl2br()
The nl2br() function conveniently converts every new line into an HTML break. So
<?php
$string = “one line\n another line\n a third for luck\n”;
echo nl2br($string);
?>

III BCom- SEMVI UNIT II Page 9


Srinivasa Degree College PHP and My SQL
output
one line<br />
another line<br />
a third for luck<br />
wordwrap()
The wordwrap() function break the lines at every 75 characters and uses \n as its line break character.
wordwrap() requires one argument: the string to transform.
<?php
$string = “Given a long line, wordwrap() is useful as a means of breaking it into a column and thereby making
it easier to read”;
echo wordwrap($string);
?>
outputs the following:
Given a long line, wordwrap() is useful as a means of breaking it into a colu
mn and thereby making it easier to read”
TOPIC 7:
Using Date and Time Functions in PHP:
PHP supports the following Date and Time functions:
Getting the Date with time()
PHP’s time() function gives all the information about the current date and time. It requires no
arguments and returns an integer.
EX:
<?php
echo time();
?>
sample output: 1326853185
This represents January 17, 2012 at 09:19PM
The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1,
1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is
referred to as a timestamp.
Converting a Timestamp with getdate()
Now that you have a timestamp to work with, you must convert it before you present it to the user.
getdate() accepts a timestamp and returns an associative array containing information about the date. Below
table lists the elements contained in the array returned by getdate().

Listing 10.4 uses getdate() in line 2 to extract information from a timestamp, employing a foreach
statement to print each element (line 3). You can see typical output of this script, called getdate.php, in
Figure 10.5. LISTING 10.4 Acquiring Date Information with getdate()
1: <?php
III BCom- SEMVI UNIT II Page 10
Srinivasa Degree College PHP and My SQL
2: $d= getdate(); // no argument passed so today’s date will be used
3: echo "today date is: $d['mon']"/" $d['mday'] "/" $d['year']";
4: ?>
It returns 03/02/2018
Converting a Timestamp with date()
Some times,you want to display the date as a string. The date() function returns a formatted string
that represents a date.
syntax: date(format,timestamp)
Some Format Codes for Use with date()

EX:
1: <?php
2: $time = time(); //stores the exact timestamp to use in this script
3: echo date(“m/d/y”, $time);
4: ?>
output:
01/17/12
Creating Timestamps with mktime()
mktime() returns a timestamp that you can then use with date() or getdate(). mktime() accepts up to
six integer arguments in the following order:
• Hour
• Minute
• Second
• Month
III BCom- SEMVI UNIT II Page 11
Srinivasa Degree College PHP and My SQL
• Day of month
• Year
EX:
1: <?php
2: // make a timestamp for Jan 17 2012 at 9:34 pm
3: $ts = mktime(21, 34, 0, 1, 17, 2012);
4: echo date(“m/d/y”, $ts);
5: ?>
Output:
01/17/12
Date/Time Functions
Function Description
date_add() Adds days, months, years, hours, minutes, and seconds to a date
Returns a new DateTime object formatted according to a
date_create_from_format()
specified format
date_create() Returns a new DateTime object
date_date_set() Sets a new date
date_default_timezone_get() Returns the default timezone used by all date/time functions
date_default_timezone_set() Sets the default timezone used by all date/time functions
date_diff() Returns the difference between two dates
date_format() Returns a date formatted according to a specified format
date_get_last_errors() Returns the warnings/errors found in a date string
date_interval_create_from_date_string() Sets up a DateInterval from the relative parts of the string
date_interval_format() Formats the interval
date_isodate_set() Sets the ISO date
date_modify() Modifies the timestamp
date_offset_get() Returns the timezone offset
Returns an associative array with detailed info about a specified
date_parse_from_format()
date, according to a specified format
Returns an associative array with detailed info about a specified
date_parse()
date
Subtracts days, months, years, hours, minutes, and seconds from
date_sub()
a date
Returns an array containing info about sunset/sunrise and
date_sun_info()
twilight begin/end, for a specified day and location
date_sunrise() Returns the sunrise time for a specified day and location
date_sunset() Returns the sunset time for a specified day and location
date_time_set() Sets the time
date_timestamp_get() Returns the Unix timestamp
date_timestamp_set() Sets the date and time based on a Unix timestamp
date_timezone_get() Returns the time zone of the given DateTime object
date_timezone_set() Sets the time zone for the DateTime object
date() Formats a local date and time

III BCom- SEMVI UNIT II Page 12


Srinivasa Degree College PHP and My SQL
Returns date/time information of a timestamp or the current
getdate()
local date/time
gettimeofday() Returns the current time
gmdate() Formats a GMT/UTC date and time
gmmktime() Returns the Unix timestamp for a GMT date
gmstrftime() Formats a GMT/UTC date and time according to locale settings
idate() Formats a local time/date as integer
localtime() Returns the local time
microtime() Returns the current Unix timestamp with microseconds
mktime() Returns the Unix timestamp for a date
strftime() Formats a local time and/or date according to locale settings
strptime() Parses a time/date generated with strftime()
strtotime() Parses an English textual datetime into a Unix timestamp
time() Returns the current time as a Unix timestamp
Returns an associative array containing dst, offset, and the
timezone_abbreviations_list()
timezone name
timezone_identifiers_list() Returns an indexed array with all timezone identifiers
timezone_location_get() Returns location information for a specified timezone
timezone_name_from_ abbr() Returns the timezone name from abbreviation
timezone_name_get() Returns the name of the timezone
timezone_offset_get() Returns the timezone offset from GMT
timezone_open() Creates new DateTimeZone object
timezone_transitions_get() Returns all transitions for the timezone
timezone_version_get() Returns the version of the timezone db

III BCom- SEMVI UNIT II Page 13

You might also like