0% found this document useful (0 votes)
347 views33 pages

PHP String Functions

This document discusses PHP string functions and functions. It provides examples of built-in PHP string functions like strlen(), str_word_count(), strrev(), etc. It also covers user-defined functions, functions with arguments, returning values from functions, and variable scopes in PHP like local, global, and static. The advantages of using functions are reduced repetition, easier code maintenance, and reusability.

Uploaded by

mufeeza
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
347 views33 pages

PHP String Functions

This document discusses PHP string functions and functions. It provides examples of built-in PHP string functions like strlen(), str_word_count(), strrev(), etc. It also covers user-defined functions, functions with arguments, returning values from functions, and variable scopes in PHP like local, global, and static. The advantages of using functions are reduced repetition, easier code maintenance, and reusability.

Uploaded by

mufeeza
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 33

PHP STRING FUNCTIONS AND FUNCTIONS

PHP String Functions

 A string is a sequence of letters, numbers, special characters and


arithmetic values or combination of all. The simplest way to create a
string is to enclose the string literal (i.e. string characters) in single
quotation marks (‘).
 Strings are the collection of Characters. Common Built-in PHP String
Functions are:
Function Description

The PHP strlen() function returns the length of a string.


strlen()
Syntax: echo strlen("Hello world!");

The PHP str_word_count() function counts the number


str_word_count() of words in a string:
Syntax: echo str_word_count("Hello world!");

Reverses a string
strrev()
Syntax: echo strrev("Hello world!");

Searches for a specific text within a string. If a match is


found, the function returns the character position of the
strpos()
first match. If no match is found, it will return FALSE.
Syntax: echo strpos("Hello world!", "world");
Replaces some characters with some other characters in a string.
str_replace()
Syntax: echo str_replace("world", "Dolly", "Hello world!");

explode() Split a string into an array by a specified string.

Converts the first character of a string to uppercase


ucfirst()
Syntax: echo ucfirst("Hello world!","Hello world!");

lcfirst() Converts the first character of a string to lowercase

strtolower() Converts a string to lowercase letters

strtoupper() Converts a string to uppercase letters

str_shuffle() Shuffles all characters in a string Randomly.


str_repeat() Repeats a string upto specified number of times.
substr() Returns a part of a string.
Removes whitespace or other characters from both
trim()
sides of a string
Return a string by joining the elements of an array with a
implode()
specified string.

Converts the first character of each word in a string


ucwords()
to uppercase
wordwrap() Wraps a string to a given number of characters
Examples

 echo strlen("Pakistan!");
 echo str_word_count("Pakistan Punjab!");
 echo strrev("Pakistan Punjab!");
 echo strpos("Pakistan Punjab!", "Punjab");
 echo str_replace("Pakistan ", "Punjab!", "Hello Pakistan!");
 echo strtolower("Pakistan Punjab");
 echo strtoupper("Pakistan Punjab");
 echo lcfirst("Pakistan Punjab!");
 echo ucfirst("Pakistan Punjab!");
 //Convert the first character of each word to uppercase:
echo ucwords("Pakistan Punjab");
 //Return "world" from the string:
echo substr("Pakistan Punjab",6);
echo substr("Pakistan Punjab",0,10)."<br>";
echo substr("Pakistan Punjab",1,8)."<br>";
echo substr("Pakistan Punjab",0,5)."<br>";
echo substr("Pakistan Punjab",6,6)."<br>";
echo "<br>";

 $arr = array('Pakistan','is','Beautiful','Country!’);
echo implode(" ",$arr)."<br>";
 $str = "Pakistan is beautiful country.";
print_r (explode(" ",$str));
Array ( [0] => Pakistan [1] => is [2] => beautiful [3] => country.)
 // break limit expload
$str = 'Lahore,Karachi,Peshawer,Quitta';
 // zero limit
print_r(explode(',',$str,0));
print "<br>";
 // positive limit
print_r(explode(',',$str,2));
print "<br>";
 // negative limit
print_r(explode(',',$str,-1));
 // case-sensitive constant name default(false)
define("GREETING", "Welcome to abc.com!",true);
echo GREETING;
PHP Function

 PHP Built-in Functions:


PHP has 1000+ built in function. PHP has a huge collection of
internal or built-in functions that you can call directly within your
PHP scripts to perform a specific task, like print_r(), var_dump, etc.
PHP User Defined Functions

 we can create our own functions.


 A function is a block of statements that can be used repeatedly in a
program.
 A function will not execute immediately when a page loads.
 A function will be executed by a call to the function.
 A user defined function declaration starts with the word "function":
 Syntax
function functionName() {
code to be executed;
}
 Note: A function name can start with a letter or underscore (not a
number).
 Tip: Give the function a name that reflects what the function does!
 Function names are NOT case-sensitive.
To call the function, just write its name:
<?php
function display() {
echo "Web Development Class!";
}

display();

?>
PHP Function with Arguments

 Information can be passed to functions through arguments. An


argument is just like a variable.
 Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma.
<?php
function firstName($fname) {
echo "$fname Is a boy.<br />";
}
firstName("Ali");
firstName("asad");
firstName("Awais");
firstName("Jameel");
?>
 In this example has a function with two arguments ($firstName and
$age):
<?php

function pdata($firstName, $age) {


echo "your first name is $firstName. And your age is $age <br />";
}

pdata("Ali", "25");
pdata("Aslam", "35");
pdata("Kamran", "21");

?>
PHP Default Value Argument

 In this example shows how to use a default parameter. If we call the


function without arguments, it takes the default value as argument:
<?php
function value($def=50) {
echo "The value is : $def <br />";
}

value(450);
value();
value(300);
value(500);
?>
PHP Functions - Returning values

 A function can return a value using the return statement. After


‘return’ the execution of the function stops and sends the return
value back to the calling code.
 To let a function return a value, use the return statement:
<?php
function sum($a, $b) {
$c = $a + $b;
return $c;
}
echo "2 + 2 = " . sum(2, 2);
echo "4 + 6 = " . sum(4, 6);
echo "3 + 9 = " . sum(3, 9);
?>
Advantages of functions

 Here are some advantages of using functions:


 Functions reduces the repetition of code within a program — Function allows
you to extract commonly used block of code into a single component. Now you
can perform the same task by calling this function wherever you want within
your script without having to copy and paste the same block of code again
and again.
 Functions makes the code much easier to maintain — Since a function created
once can be used many times, so any changes made inside a function
automatically implemented at all the places without touching the several files.
 Functions makes it easier to eliminate the errors — When the program is
subdivided into functions, if any error occur you know exactly what function
causing the error and where to find it. Therefore, fixing errors becomes much
easier.
 Functions can be reused in other application — Because a function is separated
from the rest of the script, it's easy to reuse the same function in other
applications just by including the php file containing those functions.
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
Global Scope

 A variable declared outside a function has a GLOBAL SCOPE and can


only be accessed outside a function.
 Example:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
Local Scope

 A variable declared within a function has a LOCAL SCOPE and can


only be accessed within that function.
 Example:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
PHP The global Keyword

 The global keyword is used to access a global variable from within a function. To
do this, use the global keyword before the variables (inside the function):
 Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
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:
 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.
 Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
PHP Global Variables -
Superglobals
 Several predefined variables in PHP are "superglobals", which means that they
are always accessible, regardless of scope - and you can access them from any
function, class or file without having to do anything special.
 The PHP superglobal variables are:
 $GLOBALS
 $_SERVER
 $_REQUEST
 $_POST
 $_GET
 $_FILES
 $_ENV
 $_COOKIE
 $_SESSION
Methods of Sending Information to
Server
 A web browser communicates with the server typically using one of
the two HTTP (Hypertext Transfer Protocol) methods — GET and
POST. Both methods pass the information differently and have
different advantages and disadvantages, as described below.
The GET Method

 In GET method the data is sent as URL parameters that are usually
strings of name and value pairs separated by ampersands (&). In
general, a URL with GET data will look like this:
http://www.example.com/action.php?name=john&age=24
 The bold parts in the URL are the GET parameters and the italic parts
are the value of those parameters. More than one parameter=value
can be embedded in the URL by concatenating with ampersands
(&). One can only send simple text data via GET method.
 PHP provides the superglobal variable $_GET to access all the
information sent either through the URL or submitted through an
HTML form using the method="get".
Advantages and Disadvantages of
Using the GET Method
 Since the data sent by the GET method are displayed in the URL, it is
possible to bookmark the page with specific query string values.
 The GET method is not suitable for passing sensitive information such
as the username and password, because these are fully visible in the
URL query string as well as potentially stored in the client browser's
memory as a visited page.
 Because the GET method assigns data to a server environment
variable, the length of the URL is limited. So, there is a limitation for
the total data to be sent.
 Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of PHP GET method</title>
</head>
<body>
<?php
if(isset($_GET["name"])){
echo "<p>Hi, " . $_GET["name"] . "</p>";}?>
<form method="get" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label for="inputName">Name:</label>
<input type="text" name="name" id="inputName">
<input type="submit" value="Submit">
</form>
</body>
 PHP $_POST is widely used to collect form data after submitting an HTML form
with method="post". $_POST is also widely used to pass variables.
 The example below shows a form with an input field and a submit button.
When a user submits the data by clicking on "Submit", the form data is sent to
the file specified in the action attribute of the <form> tag. In this example, we
point to the file itself for processing form data. If you wish to use another PHP file
to process form data, replace that with the filename of your choice. Then, we
can use the super global variable $_POST to collect the value of the input field:
 Example

PHP $_POST <html><body><form method="post" action="">


Name: <input type="text" name="fname"> <input type="submit"> </form>
<?php
if ($_POST["submit"]) {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name; } } ?></body></html>
Advantages and Disadvantages of
Using the POST Method
 It is more secure than GET because user-entered information is never
visible in the URL query string or in the server logs.
 There is a much larger limit on the amount of data that can be
passed and one can send text data as well as binary data
(uploading a file) using POST.
 Since the data sent by the POST method is not visible in the URL, so it
is not possible to bookmark the page with specific query.
The $_REQUEST Variable
 PHP $_REQUEST is used to collect data after submitting an HTML form.
 The example below shows a form with an input field and a submit button. When a user submits the data
by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag.
In this example, we point to this file itself for processing form data. If you wish to use another PHP file to
process form data, replace that with the filename of your choice. Then, we can use the super global
variable $_REQUEST to collect the value of the input field:
 Example
<html> <body> <form method="post" > Name: <input type="text" name="fname"> <input type="submit">
</form>
<?php
if(isset($_REQUEST[“submit"])){
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name; }}?>
</body>
</html>
When we use get and post method
in PHP?
 The POST method transfers information via HTTP headers. The
information is encoded as described in case of GET method and put
into a header called QUERY_STRING. The POST method does
not have any restriction on data size to be sent. The POST
method can be used to send ASCII as well as binary data.
null in PHP

 PHP NULL Value.


 Null is a special data type which can have only one value: NULL.
 A variable of data type NULL is a variable that has no value
assigned to it.
 Tip: If a variable is created without a value, it is automatically
assigned a value of NULL.
isset () function

 The isset () function is used to


check whether a variable is
set or not. If a variable is
already unset with unset()
function, it will no longer be
set. The isset() function return
false if testing variable
contains a NULL value.

You might also like