0% found this document useful (0 votes)
3K views

PHP Strings and Functions

PHP strings can contain letters, numbers, special characters, and values. They are created using single or double quotes, which work slightly differently. Single quotes treat strings literally while double quotes interpret escape sequences. Common string functions include strlen(), str_word_count(), and str_replace(). PHP functions are reusable blocks of code that perform tasks. They can take parameters, return values, and have different variable scopes. Functions help reduce code repetition and make code easier to maintain.

Uploaded by

Mab Shi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views

PHP Strings and Functions

PHP strings can contain letters, numbers, special characters, and values. They are created using single or double quotes, which work slightly differently. Single quotes treat strings literally while double quotes interpret escape sequences. Common string functions include strlen(), str_word_count(), and str_replace(). PHP functions are reusable blocks of code that perform tasks. They can take parameters, return values, and have different variable scopes. Functions help reduce code repetition and make code easier to maintain.

Uploaded by

Mab Shi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

PHP STRINGS

- sequence of letters, numbers, special characters and arithmetic values or combination of all
- simplest way to create a string is to enclose the string literal (i.e. string characters) in single quotation marks (')
- double quotation marks (") can also be used, however, single and double quotation marks work in different ways
- strings enclosed in single-quotes are treated almost literally
- strings delimited by the double quotes replaces variables with the string representations of their values as well as
specially interpreting certain escape sequences

The escape-sequence replacements are:


 \n is replaced by the newline character
 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)

MANIPULATING PHP STRINGS


String functions
 strlen()
- used to calculate the number of characters inside a string
- also includes the blank spaces inside the string
<?php
$my_str = 'Welcome to Tutorial Republic';

// Outputs: 28
echo strlen($my_str);
?>
 str_word_count()
- counts the number of words in a string
<?php
$my_str = 'The quick brown fox jumps over the lazy dog.';

// Outputs: 9
echo str_word_count($my_str);
?>
 str_replace() - replaces all occurrences of the search text within the target string
<?php
$my_str = 'If the facts do not fit the theory, change the facts.';

// Display replaced string


echo str_replace("facts", "truth", $my_str);
?>
The output of the above code will be:
If the truth do not fit the theory, change the truth.
 strrev() - reverses a string

<?php
$my_str = 'You can do anything, but not everything.';

// Display reversed string


echo strrev($my_str);
?>
The output of the above code will be:
.gnihtyreve ton tub ,gnihtyna od nac uoY

Reference: www.tutorialrepublic.com, www.w3schools.com


PHP FUNCTIONS

- a self-contained block of code that performs a specific task

2 types

1. Built – in Functions
2. User – defined functions

Advantages of using functions


 Functions reduces the repetition of code within a program
 Functions makes the code much easier to maintain 
 Functions makes it easier to eliminate the errors
 Functions can be reused in other application

How to create Functions and how to invoke it?


Syntax:
function functionName() {
    code to be executed;
}

Note: The declaration of a user-defined function start with the word function, followed by the name of the function you want to create
followed by parentheses i.e. () and finally place your function's code between curly brackets {}. 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.

Example:
<?php
// Defining function
function whatIsToday(){
echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>

Functions with Parameters

You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder
variables within a function; they're replaced at run time by the values (known as argument) provided to the function at the time of
invocation.

function myFunc($oneParameter, $anotherParameter){
    // Code to be executed
}

You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be
passed to the function when it is called.

The getSum() function in following example takes two integer values as arguments, simply add them together and then display the
result in the browser.

Example:
<?php
// Defining function
function getSum($num1, $num2){
$sum = $num1 + $num2;

Reference: www.tutorialrepublic.com, www.w3schools.com


echo "Sum of the two numbers $num1 and $num2 is : $sum";
}

// Calling function
getSum(10, 20);
?>
The output of the above code will be:
Sum of the two numbers 10 and 20 is : 30
Tip: An argument is a value that you pass to a function, and a parameter is the variable within the function that receives the argument.
However, in common usage these terms are interchangeable i.e. an argument is a parameter is an argument.

Functions with Optional Parameters and Default Values


You can also create functions with optional parameters — just insert the parameter name, followed by an equals (=) sign, followed by
a default value, like this.
Example:
<?php
// Defining function
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
}

// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>
As you can see the third call to customFont() doesn't include the second argument. This causes PHP engine to use the default value for
the $size parameter which is 1.5.

Returning Values from a Function


A function can return a value back to the script that called the function using the return statement. The value may be of any type,
including arrays and objects.
Example:
<?php
// Defining function
function getSum($num1, $num2){
$total = $num1 + $num2;
return $total;
}

// Printing returned value


echo getSum(5, 10); // Outputs: 15
?>
A function can not return multiple values. However, you can obtain similar results by returning an array, as demonstrated in the
following example.
Example:
<?php
// Defining function
function divideNumbers($dividend, $divisor){
$quotient = $dividend / $divisor;
$array = array($dividend, $divisor, $quotient);
return $array;
}

// Assign variables as if they were an array


list($dividend, $divisor, $quotient) = divideNumbers(10, 2);
Reference: www.tutorialrepublic.com, www.w3schools.com
echo $dividend; // Outputs: 10
echo $divisor; // Outputs: 2
echo $quotient; // Outputs: 5
?>

Passing Arguments to a Function by Reference


In PHP there are two ways you can pass arguments to a function: by value and by reference. By default, function arguments are passed
by value so that if the value of the argument within the function is changed, it does not get affected outside of the function. However,
to allow a function to modify its arguments, they must be passed by reference.
Passing an argument by reference is done by prepending an ampersand (&) to the argument name in the function definition, as shown
in the example below:
Example:
<?php
/* Defining a function that multiply a number
by itself and return the new value */
function selfMultiply(&$number){
$number *= $number;
return $number;
}

$mynum = 5;
echo $mynum; // Outputs: 5

selfMultiply($mynum);
echo $mynum; // Outputs: 25
?>

Understanding the Variable Scope


However, you can declare the variables anywhere in a PHP script. But, the location of the declaration determines the extent of a
variable's visibility within the PHP program i.e. where the variable can be used or accessed. This accessibility is known as variable
scope.

By default, variables declared within a function are local and they cannot be viewed or manipulated from outside of that function, as
demonstrated in the example below:
Example:
<?php
// Defining function
function test(){
$greet = "Hello World!";
echo $greet;
}

test(); // Outputs: Hello World!

echo $greet; // Generate undefined variable error


?>
Similarly, if you try to access or import an outside variable inside the function, you'll get an undefined variable error, as shown in the
following example:
Example:
<?php
$greet = "Hello World!";

// Defining function
function test(){
echo $greet;
}
Reference: www.tutorialrepublic.com, www.w3schools.com
test(); // Generate undefined variable error

echo $greet; // Outputs: Hello World!


?>
As you can see in the above examples the variable declared inside the function is not accessible from outside, likewise the variable
declared outside of the function is not accessible inside of the function. This separation reduces the chances of variables within a
function getting affected by the variables in the main program.

Tip: It is possible to reuse the same name for a variable in different functions, since local variables are only recognized by the function
in which they are declared.

The global Keyword


There may be a situation when you need to import a variable from the main program into a function, or vice versa. In such cases, you
can use the global keyword before the variables inside a function. This keyword turns the variable into a global variable, making it
visible or accessible both inside and outside the function, as show in the example below:
Example:
<?php
$greet = "Hello World!";

// Defining function
function test(){
global $greet;
echo $greet;
}

test(); // Outpus: Hello World!


echo $greet; // Outpus: Hello World!

// Assign a new value to variable


$greet = "Goodbye";

test(); // Outputs: Goodbye


echo $greet; // Outputs: Goodbye
?>

Creating Recursive Functions


A recursive function is a function that calls itself again and again until a condition is satisfied. Recursive functions are often used to
solve complex mathematical calculations, or to process deeply nested structures e.g., printing all the elements of a deeply nested array.
The following example demonstrates how a recursive function works.
Example:
<?php
// Defining recursive function
function printValues($arr) {
global $count;
global $items;

// Check input is an array


if(!is_array($arr)){
die("ERROR: Input is not an array");
}

/*
Loop through array, if value is itself an array recursively call the
function else add the value found to the output items array,
and increment counter by 1 for each value found
Reference: www.tutorialrepublic.com, www.w3schools.com
*/
foreach($arr as $a){
if(is_array($a)){
printValues($a);
} else{
$items[] = $a;
$count++;
}
}

// Return total count and values found in array


return array('total' => $count, 'values' => $items);
}

// Define nested array


$species = array(
"birds" => array(
"Eagle",
"Parrot",
"Swan"
),
"mammals" => array(
"Human",
"cat" => array(
"Lion",
"Tiger",
"Jaguar"
),
"Elephant",
"Monkey"
),
"reptiles" => array(
"snake" => array(
"Cobra" => array(
"King Cobra",
"Egyptian cobra"
),
"Viper",
"Anaconda"
),
"Crocodile",
"Dinosaur" => array(
"T-rex",
"Alamosaurus"
)
)
);

// Count and print values in nested array


$result = printValues($species);
echo $result['total'] . ' value(s) found: ';
echo implode(', ', $result['values']);
?>

Reference: www.tutorialrepublic.com, www.w3schools.com


Note: Be careful while creating recursive functions, because if code is written improperly it may result in an infinite loop of function
calling.

Reference: www.tutorialrepublic.com, www.w3schools.com

You might also like