3. Strings in PHP
● Strings are sequences of characters that can be treated as a
unit — assigned to variables, given as input to functions,
returned from functions, or sent as output to appear on your
user’s web page
● The simplest way to specify a string in PHP code is to enclose
it in quotation marks, whether single quotation marks (‘) or
double quotation marks (“), like this:
○ $my_string = ‘A literal string’;
○ $another_string = “Another string”;
4. Interpolation with curly braces
● When variable interpolation with curly braces is done actually tells the parser
about the start and end of the variable
● Php will evaluate a variable starting with a { and ending with a } and
interpolate the rest of the string as it is
● Example:
<?php
$sports= "cricket";
echo "I will play {$sports}in the summer time";
?>
5. String operators
● PHP offers two string operators: the dot (.) or concatenation operator and the .=
concatenating assignment operator.
Concatenation operator
● The concatenation operator, when placed between two string arguments, produces a new string
that is the result of putting the two strings together in sequence.
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
Output: Hello world!
6. Concatenation assignment
● PHP has a shorthand operator (.=) that combines concatenation with assignment.
● Appends $txt2 to $txt1
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2; //($txt1 = $txt1.$txt2;)
echo $txt1;
?>
Output: Hello world!
7. Heredoc
● PHP offers another way to specify a string, called the heredoc syntax
● Heredoc PHP syntax is a way to write large block of text inside PHP, without the classic single
quote, double quotes delimiters.
● The operator in the heredoc syntax is <<<.
<?php
echo <<<mystring
Everything in this rather unnecessarily wordy
ramble of prose will be incorporated into the
string that we are building up inevitably, inexorably,
character by character, line by line, until we reach that
blessed final line which is this one.
mystring;
?>
Output:
Everything in this rather
unnecessarily wordy ramble of
prose will be incorporated into
the string that we are building up
inevitably, inexorably, character
by character, line by line, until we
reach that blessed final line
which is this one.
8. String Functions
● The PHP string functions are part of the PHP core.
1.Inspecting strings
● First on the list is how long the string is, using the strlen() function
● strlen() function returns the length of the string
● Example
<?php
$s="hello world";
echo strlen($s);
?>
Output: 11
9. String Functions
2.Finding characters and substrings
● The strpos() function finds the numerical position of a particular character in a string, if it
exists.
● Example
<?php
$s="hello world";
echo strpos($s,'w');
?>
Output: 6
10. String Functions
● The strrpos() function finds the position of the last occurrence of a string inside another string.
Related functions:
● strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)
● stripos() - Finds the position of the first occurrence of a string inside another string (case-
insensitive)
● strripos() - Finds the position of the last occurrence of a string inside another string (case-
insensitive)
● Example
<?php
$s="hello world";
echo strrpos($s,'l');
?>
Output: 9
11. String Functions
3.Comparison and searching
Comparing
The strncmp() function compares two strings.
Note: The strncmp() is binary-safe and case-sensitive.
This function is similar to the strcmp() function, except that strcmp() does not have the length
parameter.
Example:
<?php
$s1="hello";
$s2="Hello";
if (strncmp($s1,$s2,5)==0)
echo "the strings are equal";
else
echo "the strings are not equal";
?>
Output: the strings are not equal
12. String Functions
3.Comparison and searching
Comparing
The strncasecmp() function compares two strings.
Note: The strncasecmp() is binary-safe and case-insensitive.
Tip: This function is similar to the strcasecmp() function, except that strcasecmp() does not have the
length parameter.
Example:
<?php
$s1="hello";
$s2="Hello";
if (strncasecmp($s1,$s2,5)==0)
echo "the strings are equal";
else
echo "the strings are not equal";
?>
Output: the strings are equal
13. String Functions
Searching
Comparing
● The strstr() function searches for the first occurrence of a string inside another string.
● This function is case-sensitive. For a case-insensitive search, use stristr() function.
● strchr() Identical to strstr().
● stristr() Identical to strstr() except that the comparison is case independent.
Example:
<?php
$s="Hello world!";
echo strstr($s,"world");
?>
Output: world
14. String Functions
Substring selection
● The substr() function returns a part of a string.
● The substring starts at the indicated position and continues for as many characters as
specified by the length argument or until the end of the string, if there is no length argument.
Example:
<?php
$s="Hello world";
echo substr($s,6);
?>
Output: world
15. String Functions
String cleanup functions
● The functions chop(), ltrim(), and trim() are really used for cleaning up untidy strings.
● The chop() (rtrim())function removes whitespaces or other predefined characters from the right end
of a string.
● The trim() function removes whitespace and other predefined characters from both sides of a string.
● ltrim() - Removes whitespace or other predefined characters from the left side of a string
Example:
<?php
$str = "Hello World!";
echo $str;
echo chop($str,"World!");
?>
Output: Hello World!Hello
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
Hello World!
llo Worl
<?php
$str = "Hello World!";
echo $str . "<br>";
echo ltrim($str,"Hello");
?>
Hello World!
World!
16. String Functions
String replacement
● The str_replace() function replaces some characters with some other characters in a string.
● str_replace(find,replace,string,count)
● The substr_replace() function replaces a part of a string with another string.
● substr_replace(string,replacement,start,length)
Example:
<?php
$s="hello world";
echo str_replace("hello", "welcome",$s);
?>
Output: welcome world
<?php
$s="hello";
echo substr_replace($s,"world",1); // 0 will start
replacing at the first character in the string
?>
Output:hworld
17. String Functions
Case functions
1. strtolower()
The strtolower() function returns an all-lowercase string. It doesn’t matter if the original is all
uppercase or mixed. This fragment:
<?php
$original = “They DON’T KnoW they’re SHOUTING”;
$lower = strtolower($original);
echo $lower;
?>
returns the string “they don’t know they’re shouting”.
2.strtoupper()
The strtoupper() function returns an all-uppercase string, regardless of whether the original was
all lowercase or mixed:
<?php
$original = “make this link stand out”;
echo(“<B>strtoupper($original)</B>”);
?>
18. String Functions
Case functions
3.ucfirst()
The ucfirst() function capitalizes only the first letter of a string:
<?php
$original = “polish is a word for which pronunciation depends on
capitalization”;
echo(ucfirst($original));
?>
4.ucwords()
The ucwords() function capitalizes the first letter of each word in a string:
<?php
$original = “truth or consequences”;
$capitalized = ucwords($original);
echo “While $original is a parlor game, $capitalized is a town in New
Mexico.”;
?>
19. PHP Arrays
Array
● An array is a collection of variables indexed and bundled into a single, easily
referenced super variable that offers an easy way to pass multiple values between
lines of code, functions, and even pages.
Creating Arrays
There are three main ways to create an array in a PHP script:
● by assigning a value into one (and thereby implicitly creating it),
● by using the array() construct, and
● by calling a function that happens to return an array as its value.
20. 1.Direct assignment
The simplest way to create an array is to act as though a variable is already an array and assign a
value into it
Example:
$myarray[1]=” This is my car”
2. The array() construct()
array() function is used to create an array
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Output:
Volvo
BMW
Toyota
21. Specifying indices using array() (Associative Array)
● Associative arrays are arrays that use named keys that you assign to them.
<?php
$fruit = array(10=> "apple", 20=> "orange");
foreach ($fruit as $x => $x_value)
{
echo "key=".$x;
echo "value=".$x_value."<br>";
}
?>
Output:
key=10 value=apple
key=20 value=orange
22. Functions returning arrays
● The final way to create an array in a script is to call a function that returns an array.
This may be a user defined function, or it may be a built-in function that makes an
array via methods internal to PHP.
<?php
$myarray = range(1,5);
for($i=0;$i<6;$i++)
{
echo $myarray[$i];
}
?>
Output
12345
23. Retrieving Values
1.Retrieving by index
The most direct way to retrieve a value is to use its index.
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[1];
?>
output
BMW
24. Retrieving Values
2.list() construct
● The list() function is an inbuilt function in PHP which is used to assign array values to multiple
variables at a time.
● It accepts a list of variables separated by spaces. These variables are assigned values. At
least one variable must be passed to the function.
<?php
$my_array = array("Dog","Cat","Horse");
list($a, ,$c) = $my_array;// list($a,$b ,$c) = $my_array,list($, ,$c) = $my_array
echo "I like $a and $c.";
?>
output
I like Dog and Horse.
25. Multidimensional Arrays
● A multidimensional array is an array containing one or more arrays.
<?php
$fruits = array (
array("apple",22,18),
array("orange",15,13),
array("banana",5,2),
);
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
echo $fruits[$i][$j]."<br>";
}}
?>
output
apple
22
18
orange
15
13
banana
5
2
26. Inspecting Arrays
Simple Functions for Inspecting Arrays
1.is_array()
Takes a single argument of any type and returns a true value if the argument is an array, and false otherwise
Example
<?php
$a = "Hello";
echo "a is " . is_array($a) . "<br>";
$b = array("red", "green", "blue");
echo "b is " . is_array($b) . "<br>";
?>
Output:
a is
b is 1
27. Inspecting Arrays
2.count() and sizeof()
Takes an array as argument and returns the number of nonempty elements in the array.
Example
<?php
$fruits=array("apple","orange","banana");
echo count($cars);
?>
3.in_array()
The in_array() function searches an array for a specific value.
Takes two arguments: an element and an array
Returns true if the element is contained as a value in the array, false otherwise.
<?php
$fruits = array("apple", "orange", "banana");
if(in_array("apple", $fruits))
echo "match found";
else
echo "not found";
?>
Output:
3
Output:
Match found
28. Inspecting Arrays
4.isset($array[$key])
Takes an array[key] form and returns true if the key portion is a valid key for the array.
<?php
$fruit = array(10=>"apple",20=>"banana");
echo isset($fruit[10]);
?>
output
1
29. Deleting from Arrays
unset()
This function is used to delete an element from an array
<?php
$fruits = array("apple", "orange", "banana");
unset($fruits[2]);
for($i=0;$i<3;$i++)
{
echo $fruits[$i];
}
?>
output
appleorange
30. Iteration
● Each array remembers a particular stored key/value pair as being the current one, and
array iteration functions work in part by shifting that current marker through the internal
list of keys and values.
● The linked-list pointer system is an alternative way to inspect and manipulate arrays, which
exists alongside the system that allows key-based lookup and storage
Iteration methods
● foreach
● current() and next()
● reset()
● end() and prev()
● key()
● each()
● array_walk()
31.
32. Foreach
● The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
● For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
Example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
Output:
red
green
blue
yellow
33. Current() and next()
● The current() function returns the value of the current element in an array
● The next() function moves the internal pointer to, and outputs, the next element in the array.
Example:
<?php
$fruits = array("Apple","Banana","Orange","Grapes");
echo current($fruits) . "<br>";
echo next($fruits);
?>
Output:
Apple
Banana
34. reset()
● The reset() function moves the internal pointer to the first element of the array.
Example:
<?php
$fruits = array("Apple","Banana","Orange","Grapes");
echo current($fruits) . "<br>";
echo next($fruits). "<br>";
echo reset($fruits);
?>
Output:
Apple
Banana
Apple
35. end() and prev()
● The end() function moves the internal pointer to, and outputs, the last element in the array.
● The prev() function moves the internal pointer to, and outputs, the previous element in the array.
Example:
<?php
$fruits = array("Apple","Banana","Orange","Grapes");
echo current($fruits) . "<br>";
echo end($fruits). "<br>";
echo prev($fruits);
?>
Output:
Apple
Grapes
Orange
36. key()
● The key() function returns the element key from the current internal pointer position.
Example:
<?php
$fruits = array("Apple","Banana","Orange","Grapes");
echo "The key from the current position is: " . key($fruits);
?>
Output:
The key from the current position is: 0
37. each()
● The each() function returns the current element key and value, and moves the internal pointer
forward.
Example:
<?php
$fruits = array(10=>"Apple",20=>"Banana",30=>"Orange",40=>"Grapes");
while($a=each($fruits))
{
$k=$a['key'];
$v=$a['value'];
echo $k. $v."<br>";
}
?>
Output:
10Apple
20Banana
30Orange
40Grapes
38. array_walk()
● The array_walk() function runs each array element in a user-defined function. The array's
keys and values are parameters in the function.
Example:
<?php
function myfunction($value,$key)
{
echo "The key $key has the value $value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction");
?>
Output:
The key a has the value red
The key b has the value green
The key c has the value blue
39.
40.
41. Numerical Types
● PHP has only two numerical types:
○ integer (also known as long), and
○ double (also known as float), which correspond to the largest numerical types in the C
language.
● PHP does automatic conversion of numerical types, so they can be freely intermixed in
numerical expressions, and the “right thing” will typically happen. PHP also converts strings
to numbers where necessary.
● In situations where you want a value to be interpreted as a particular numerical type, you
can force a typecast by prepending the type in parentheses, such as:
○ (double) $my_var
○ (integer) $my_var
● Or you can use the functions intval() and doubleval(), which convert their arguments to
integers and doubles, respectively.
43. Incrementing operators
● The increment operator (++) adds one to the variable it is attached to, and the decrement
operator (--) subtracts one from the variable.
● Each one comes in two flavors, postincrement (which is placed immediately after the
affected variable), and preincrement (which comes immediately before).
● Both flavors have the same side effect of changing the variable’s value, but they have
different values as expressions.
● The postincrement operator acts as if it changes the variable’s value after the
expression’s value is returned, whereas the preincrement operator acts as though it makes
the change first and then returns the variable’s new value
44. Assignment operators
● All five arithmetic operators have corresponding assignment operators (+=, -=, *=, /=, and %=) that
assign to a variable the result of an arithmetic operation on that variable in one fell swoop.
● The statement:
○ $count = $count * 3;
can be shortened to:
■ $count *= 3;
● and the statement:
○ $count = $count + 17;
Becomes:
$count += 17;
45. Comparison operators
● PHP includes the standard arithmetic comparison operators, which take simple values (numbers or strings) as
arguments and evaluate to either TRUE or FALSE:
● The < (less than) operator is true if its left-hand argument is strictly less than its right-hand argument but
false otherwise.
● The > (greater than) operator is true if its left-hand argument is strictly greater than its right-hand
argument but false otherwise.
● The <= (less than or equal) operator is true if its left-hand argument is less than or equal to its right-hand
argument but false otherwise.
● The >= (greater than or equal) operator is true if its left-hand argument is greater than or equal to its right-
hand argument but false otherwise.
● The == (equal to) operator is true if its arguments are exactly equal but false otherwise.
● The != (not equal) operator is false if its arguments are exactly equal and true otherwise.
● This operator is the same as <>.
● The === operator (identical to) is true if its two arguments are exactly equal and of the same type.
● The !== operator (not identical to) is true if the two arguments are not equal or not of the same type.
46. Precedence and parentheses
● Operator precedence rules govern the relative stickiness of operators, deciding which
operators in an expression get first claim on the arguments that surround them
● Arithmetic operators have higher precedence (that is, bind more tightly) than comparison
operators.
● Comparison operators have higher precedence than assignment operators.
● The *, /, and % arithmetic operators have the same precedence.
● The + and – arithmetic operators have the same precedence.
● The *, /, and % operators have higher precedence than + and –.
● When arithmetic operators are of the same precedence, associativity is from left to right
(that is, a number will associate with an operator to its left in preference to the operator on
its right).
● Example: 1 + 2 * 3 - 4 - 5 / 4 % 3
■ Answer is 2 (((1 + (2 * 3)) – 4) – ((5 / 4) % 3))
50. rand()
● The rand() function generates a random integer.
Example:
<?php
echo(rand() . "<br>");
echo(rand() . "<br>");
echo(rand(10,100));
?>
Output:
512549293
1132363175
79
51. srand()
● The srand() function seeds the random number generator (rand()).
Example:
<?php
srand(mktime());
echo(rand());
?>
Output:
32857050
52. getrandmax()
● The getrandmax() function returns the largest possible value that can be returned by rand().
Example:
<?php
echo(getrandmax());
?>
Output:
2147483647
53. mt_rand()
● The mt_rand() function generates a random integer using the Mersenne Twister algorithm.
Example:
<?php
echo(mt_rand() . "<br>");
echo(mt_rand() . "<br>");
echo(mt_rand(10,100));
?>
Output:
753337239
811653027
45
54. mt_srand()
● The mt_srand() function seeds the Mersenne Twister random number generator.
Example:
<?php
mt_srand(mktime());
echo(mt_rand());
?>
Output:
1749664286
55. mt_getrandmax()
● The mt_getrandmax() function returns the largest possible value that can be returned by
mt_rand().
Example:
<?php
echo(mt_getrandmax());
?>
Output:
2147483647