Chapter One
Server Side Scripting
Outline
⚫ Introduction to server-side scripting
⚫ Server-side scripting languages
⚫ Use Basic Syntax
⚫ Write Comments
⚫ Utilize Variables
⚫ Manipulate Strings
⚫ Manipulate Numbers
⚫ Work with constants
Introduction
⚫ How does the web work (revision)?
⚫ It uses the HTTP (Hyper Text Transfer Protocol) to
communicate between a client and a server
⚫ The request ranges from simple get request to fetch a static
content to post and delete requests to add or delete resources
on the server
⚫ Every request and response contains a header and optional
body
⚫ Servers are always on and listen to requests from clients
and handle them accordingly
Cont...
● Communication Scenarios
− Static content
Cont...
● Dynamic content
Server Side vs Client Side Scripting
Languages
⚫ Client side scripts
⚫ Are executed by the client, particularly by the browser
⚫ They are used for appearance and behavior of a web
page
⚫ It has little or no access to the underlying operating
system
⚫ Some features may not work or may not be properly
rendered on specific browser(s)
Server Side vs Client Side Scripting
Languages
⚫ Server Side Scripting Language
⚫ A server-side scripting language is a script executed on
the server, as opposed to client-side scripting languages
like JavaScript.
⚫ It requires a server-side scripting engine
⚫ It has full access to the server's operating system
⚫ There are a variety of server-side scripting languages,
including PHP, Python, Ruby, C#, and JavaScript (via
Node.js), among others
When to use server-side scripting
⚫ When developing Dynamic web pages
⚫ Authentication, authorization and session tracking.
⚫ Personalization and customization of content based on
authentication and authorization. This also includes the
serving of content based on the content of the page (e.g.
YouTube, Amazon, Facebook) or the browsing behavior of
the user.
When to use server-side scripting
⚫ Template-driven page generation. Including repeated
content like header/footers and navigation menus around
the “content area” of a web page.
⚫ Handling POST form input
⚫ Communication with other programs, libraries and APIs –
e.g. sending out e-mail
What Is PHP?
⚫ PHP (Hypertext Protocol) is Open Source Programming
Language used to make web pages.
⚫ PHP language can run on various platforms and is
compatible with almost all servers.
⚫ PHP files use .php as their extension.
⚫ PHP can perform functions, like creating, opening,
reading, writing, and closing files on a system
⚫ PHP can also perform functions like adding, deleting, and
modifying elements within a database
What Is PHP?
⚫ PHP can restrict users from accessing some pages of your
website
⚫ PHP can encrypt data too
⚫ PHP is widely-used, open-source language suited for web
development.
⚫ PHP is free to download and runs on various platforms
(Windows, Linux, macOS).
⚫ PHP is interpreted on the server before sending the result
to the browser.
⚫ PHP requires a web server (e.g., Apache) or local
development environment (e.g., XAMPP) to run.
The Apache Web Server
⚫ A web server is a type of computer software and its
underlying hardware that accepts requests via HTTP or its
secure variant HTTPS.
⚫ The Apache HTTP Server is a free and open-source
cross-platform web server, released under the terms of
Apache License 2.0.
⚫ Apache doesn’t serve up just HTML files—it handles a
wide range of files, from images to MP3 audio files, RSS
(Really Simple Syndication) feeds, and so on.
⚫ More importantly, these files don’t always have to be
pre-existing static files; they can be dynamically generated
using server-side programs like PHP.
WAMP, MAMP, or LAMP?
⚫ WAMP, MAMP, and LAMP are software packages that help
set up a local web server for development.
⚫ WAMP (Windows, Apache, MySQL, PHP) is for Windows.
⚫ MAMP (Mac, Apache, MySQL, PHP) is for Mac.
⚫ LAMP (Linux, Apache, MySQL, PHP) is for Linux.
⚫ They are easy to set up but are only for development and
testing—not for live websites—because they are not secure
enough for public use.
XAMPP
⚫ XAMPP is an open-source web server solution package.
⚫ It is mainly used for web application testing on a local host
webserver.
⚫ XAMPP stands for:
⚫ X = Cross-platform
⚫ A = Apache Server
⚫ M = MariaDB/MySQL
⚫ P = PHP
⚫ P = Perl
Why do we need xampp?
⚫ Enables development and testing of websites on a local
machine without requiring an internet connection or live
server.
⚫ Provides PHP and MySQL/MariaDB support, for backend
development and database integration.
⚫ Works on Windows, macOS, and Linux, ensuring
flexibility across different operating systems.
⚫ Bundles Apache, MySQL, and PHP together, reducing the
complexity of manual installation and configuration.
⚫ Allows testing websites and applications locally to catch
errors before going live.
PHP Syntax
⚫ PHP code is placed between <?php and ?>.
⚫ One or more PHP code blocks can be embedded in an
HTML file.
⚫ Case Sensitivity
⚫ Function names are not case-sensitive, but variable names
are.
⚫ Example
⚫ <?php
⚫ $x = 5;
⚫ $y = 10;
⚫ echo $x + $y;
⚫ ?>
PHP code blocks can be embedded in an HTML
file
⚫ <!DOCTYPE html>
⚫ <html>
⚫ <head>
⚫ <title>PHP</title>
⚫ </head>
⚫ <body>
⚫ <h1>
⚫ <?php
⚫ echo "hii GeeksforGeeks "
⚫ ?>
⚫ </h1>
⚫ </body>
⚫ </html>
PHP Comments
⚫ Single-Line Comments
⚫ // comment here
⚫ # comment here
⚫ Multi-Line Comments
⚫ /* multiple lines of comments here */
⚫ Usage
⚫ Use comments to explain code logic or temporarily
disable code segments.
PHP Case Sensitivity
⚫ In PHP, keywords (e.g. if, else, while, echo, etc.), classes,
functions, and user-defined functions ARE NOT
CASE-SENSITIVE.
⚫ all three echo statements below are equal and legal:
⚫ <?php
⚫ ECHO "Hello World!<br>";
⚫ echo "Hello World!<br>";
⚫ EcHo "Hello World!<br>";
⚫ ?>
⚫ Note: However; all variable names are case-sensitive!
PHP Variables
⚫ In PHP, a variable starts with the $ sign, followed by the
name of the variable:
⚫ $x = 5;
⚫ $y = "John";
⚫ 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 _ )
⚫ Unlike other programming languages, PHP has no
command for declaring a variable. It is created the
moment you first assign a value to it.
PHP is a Loosely Typed Language
⚫ PHP automatically associates a data type to the variable,
depending on its value.
⚫ Since the data types are not set in a strict sense, you can do
things like adding a string to an integer without causing an
error.
⚫ In PHP 7, type declarations were added.
⚫ This gives an option to specify the data type expected
when declaring a function,
⚫ By enabling the strict requirement, it will throw a "Fatal
Error" on a type mismatch
Variable Types
⚫ PHP has no command for declaring a variable, and the
data type depends on the value of the variable.
⚫ $x = 5; // $x is an integer
⚫ $y = "John"; // $y is a string
⚫ echo $x;
⚫ echo $y;
⚫ PHP supports the following data types:
⚫ String, Integer, Float, Boolean, Array, Object, NULL,
Resource
PHP Data Types
⚫ Strings: Text in quotes ("Hello World").
⚫ Integers: Non-decimal numbers (positive, negative, or
zero).
⚫ Floats (Doubles): Decimal numbers or those in exponential
form.
⚫ Booleans: True or false values.
⚫ Arrays: Collections of values in one variable.
⚫ Objects: Hold both data and methods related to that data.
⚫ NULL: Variable with no value assigned.
⚫ Resources: Special references (like database connections).
Revision questions
1. What is the difference between client side and server side
scripting languages
2. Give examples of server side scripting languages
3. List out components of the “web”
4. Why do we need XAMPP?
5. How do you declare a variable in PHP?
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
⚫ $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
⚫ 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):
⚫ $x = 5;
⚫ $y = 10;
⚫ function myTest() {
⚫ global $x, $y;
⚫ $y = $x + $y;
⚫}
⚫ myTest();
⚫ echo $y; // outputs 15
PHP The global Keyword
⚫ PHP also stores all global variables in an array called
$GLOBALS[index]. The index holds the name of the
variable.
⚫ This array is also accessible from within functions and can
be used to update global variables directly.
⚫ $x = 5;
⚫ $y = 10;
⚫ function myTest() {
⚫ $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
⚫ }
What will be the output
What will be the output
What will be the output
PHP Echo / Print
⚫ Echo
⚫ Outputs one or more strings, does not return a value.
⚫ Can handle multiple parameters separated by commas.
⚫ Print
⚫ Outputs a single string and always returns 1.
⚫ Slightly slower compared to echo in most cases.
⚫ Example
⚫ <?php
⚫ echo "Hello", " World!";
⚫ print "Hello World!";
⚫ ?>
Control Structures in PHP
34
Control Structure
⚫ PHP has a number of control structures to change this
default order of execution
⚫ Conditionals: Statements like if and switch that execute or
skip statements depending on the value of an expression
⚫ Loops: Statements like while and for that execute other
statements repetitively
⚫ Jumps: Statements like break, return, and throw that cause the
interpreter to jump to another part of the program
35
PHP if, else, and else if
⚫ Conditional statements are used to perform different
actions based on different conditions.
36
Revision questions
1. Write a program that checks if a number is positive,
negative, or zero. Log the result to the console.
2. Write a program that checks a student's grade and logs
the performance level:
⚫ If the grade is 90 or above, log "Excellent".
⚫ If the grade is between 70 and 89, log "Good".
⚫ If the grade is between 50 and 69, log "Average".
⚫ Otherwise, log "Fail".
37
PHP For Loop
⚫ PHP supports different kinds of loops:
⚫ for - loops through a block of code a number of times
⚫ while - loops through a block of code while a specified
condition is true
⚫ do/while - also loops through a block of code while a
specified condition is true
38
For loop
⚫ The for loop is used when the number of iterations is
known. It consists of three parts: initialization, condition,
and increment/decrement.
⚫ Syntax:
⚫ for (initialization; condition; increment/decrement)
⚫ {
⚫ // code block to execute
⚫ }
39
while Loop
⚫ The while loop executes as long as the specified condition
evaluates to true.
⚫ Syntax:
⚫ while (condition)
⚫ {
⚫ // code block to execute
⚫ }
40
do...while Loop
⚫ The do...while loop executes the block of code once before
checking the condition. It is guaranteed to execute at least
once.
⚫ Syntax:
⚫ do {
⚫ // code block to execute
⚫ } while (condition);
41
takeaway question
1. Write a PHP program to print all even numbers between
1 and 100
2. Write a for loop that prints the numbers from 1 to 10, but
skips 5
3. Write a while loop that prints numbers from 1 to 100
42
PHP Strings
⚫ Strings in PHP are surrounded by either double quotation
marks, or single quotation marks.
⚫ Double quoted string literals perform operations for special
characters:
⚫ $x = "John";
⚫ echo "Hello $x";
⚫ Single quoted strings does not perform such actions, it
returns the string like it was written, with the variable
name:
⚫ $x = "John";
⚫ echo 'Hello $x';
String Functions
⚫ The PHP strlen() function returns the length of a string.
⚫ echo strlen("Hello world!"); //12
⚫ The PHP str_word_count() function counts the number
of words in a string.
⚫ echo str_word_count("Hello world!"); //2
⚫ The PHP strpos() function searches for a specific text
within a string.
⚫ If a match is found, the function returns the character
position of the first match. If no match is found, it will
return FALSE.
⚫ echo strpos("Hello world!", "world"); //6
⚫ l
Takeaway questions
1. What will be the output of the following code:
⚫ $x = 5;
⚫ echo 'The price is $x';
2. What will be the output of echo strlen(" Learning PHP is
fun");?
3. What will echo str_word_count(" PHP is awesome!");
output?
4. What does strpos(“Let's write some code!" ,“code") return?
PHP - Modify Strings
⚫ The strtoupper() function returns the string in upper case:
⚫ $x = "Hello World!";
⚫ echo strtoupper($x);
⚫ The strtolower() function returns the string in lower case:
⚫ $x = "Hello World!";
⚫ echo strtolower($x);
⚫ The PHP str_replace() function replaces some characters
with some other characters in a string.
⚫ $x = "Hello World!";
⚫ echo str_replace("World", "Dolly", $x);
PHP - Modify Strings
⚫ The PHP strrev() function reverses a string.
⚫ $x = "Hello World!";
⚫ echo strrev($x);
⚫ The trim() removes any whitespace from the beginning or
the end:
⚫ $x = " Hello World! ";
⚫ echo trim($x);
⚫ The PHP explode() function splits a string into an array.
⚫ The first parameter of the explode() function represents
the "separator". The "separator" specifies where to split the
string
⚫ $x = "Hello World!";
⚫ $y = explode(" ", $x);
Takeaway questions
1. What will be the output of the following code?
⚫ $x = " PHP is fun! ";
⚫ echo trim($x);
2. What will be the output?
⚫ $x = "apple,banana,orange";
⚫ $y = explode(",", $x);
⚫ Echo $y[0];
3. What will be the output of this code?
⚫ $x = "Hello World!";
⚫ echo str_replace("o", "0", $x);
PHP Casting
⚫ Cast Syntax
⚫ (int) $variable, (float) $variable, (bool) $variable, etc.
⚫ Usage
⚫ Ensures a value is treated as the desired data type.
⚫ Commonly done when mixing data from forms, URLs, or text
to numeric operations.
⚫ Example
⚫ <?php
⚫ $var = "3.14";
⚫ $intVar = (int)$var; // becomes 3
⚫ ?>
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).
⚫ Unlike variables, constants are automatically global across the
entire script.
⚫ To create a constant, use the define() function
⚫ define(name, value);
⚫ define("ROOT_LOCATION", "/usr/local/www/");
⚫ To read the contents of the variable, you just refer to it like
a regular variable (but it isn’t preceded by a dollar sign):
⚫ $directory = ROOT_LOCATION;
PHP Constants cont’d
⚫ Constants are automatically global and can be used across
the entire script.
PHP Magic Constants
⚫ Predefined Constants
⚫ __LINE__ - Current line number.
⚫ __FILE__ - Full path and filename.
⚫ __DIR__ - Directory of the file.
⚫ __FUNCTION__, __CLASS__, __METHOD__,
__NAMESPACE__.
⚫ Example
⚫ <?php
⚫ echo "This is line " . __LINE__ . " of file " . __FILE__;
⚫ ?>
PHP Functions
⚫ PHP has more than 1000 built-in functions, and in
addition you can create your own custom functions.
⚫ A function is a block of statements that can be used
repeatedly in a program.
⚫ A function will not execute automatically when a page
loads.
⚫ A function will be executed by a call to the function.
⚫ A user-defined function declaration starts with the
keyword function, followed by the name of the function:
Passing Arguments
⚫ Passing by value
⚫ The original variable’s value will not be changed even if
the recipient variable value is changed.
⚫ Passing by reference
⚫ is done by appending an ampersand to the front of the
parameter(s).
⚫ It changes the original variable's value.
⚫ To pass by reference use & before the parameter name
Default and Optional arguments
⚫ Default values can be assigned to input arguments, which
will be automatically assigned to the parameter if no other
value is provided.
⚫ E.g. function salestax($price,$tax=.0575)
⚫ You can designate certain arguments as optional by
placing them at the end of the list and assigning them a
default value of nothing.
⚫ function salestax($price,$tax="")
Variable Number of Arguments
⚫ By using the ... operator in front of a function parameter, a
function accepts an unknown number of arguments.
⚫ This is also called a variadic function.
⚫ The variadic function argument becomes an array.
Variable Number of Arguments
⚫ You can only have one argument with variable length, and
it has to be the last argument.
⚫ In PHP 7, type declarations were added. This gives us an
option to specify the expected data type when declaring a
function,
⚫ When adding the strict declaration, if the data type
mismatches, it will throw a "Fatal Error“.
⚫ <?php declare(strict_types=1);
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
⚫ ?>
Array
⚫ Array is a variable that can store more than one value.
There are two ways used to create an array.
⚫ Informally
⚫ you can create the array simply by making reference to it.
⚫ $state[0] = "Delaware";
⚫ Formally
⚫ Uses the array() function
⚫ array array([item1 [,item2 ... [,itemN]]])
⚫ $languages = array ("English", "Gaelic", "Spanish");
⚫ $languages = array ("Spain" => "Spanish","Ireland" => "Gaelic",
"United States" => "English");
Indexed arrays
⚫ There are two ways to create indexed arrays.
⚫ $cars = array("Volvo", "BMW", "Toyota");
⚫ Or
⚫ $cars[0] = "Volvo";
⚫ $cars[1] = "BMW";
⚫ $cars[2] = "Toyota"
Associative Arrays
⚫ Associative arrays are arrays that use named keys that you
assign to them.
⚫ There are two ways to create an associative array:
⚫ $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
⚫ Or
⚫ $age['Peter'] = "35";
⚫ $age['Ben'] = "37";
⚫ $age['Joe'] = "43";
Array functions
⚫ range()
⚫ The range() function provides an easy way to quickly
create and fill an array consisting of a range of low and
high integer values.
⚫ $die = range(0,6);
⚫ Same as specifying $die = array(0,1,2,3,4,5,6)
⚫ The optional step parameter offers a convenient means
for determining the increment between members of the
range.
⚫ $even = range(0,20,2);
⚫ also be used for character sequences
⚫ $letters = range("A","F");
Outputting Array
⚫ print_r() is used to print the structure of arrays and objects in
an easy-to-read format.
⚫ Example:
⚫ To capture the output of print_r(), the return parameter is
used.
⚫ When this parameter is set to true, print_r() will return the
information rather than print it.
Adding and Removing array elements
⚫ array_push()
⚫ The array_push() function adds variable onto the end of the
target_array.
⚫ $states = array("Ohio","New York");
⚫ array_push($states,"California","Texas");
⚫ array_pop()
⚫ The array_pop() function returns the last element from
target_array.
⚫ $states = array("Ohio","New York","California","Texas");
⚫ $state = array_pop($states); // $state = "Texas"
Adding and Removing array elements
⚫ array_shift()
⚫ The array_shift() function is similar to array_pop(), except
that it returns the first array item found on the target_array
rather than the last.
⚫ $states = array("Ohio","New York","California","Texas");
⚫ $state = array_shift($states);
⚫ array_unshift()
⚫ The array_unshift() function is similar to array_push(),
except that it adds elements to the front of the array rather
than to the end.
⚫ $states = array("Ohio","New York");
⚫ array_unshift($states,"California","Texas");
Takeaway question 1
⚫ Given the following array, $fruits = ["apple", "banana"];
⚫ Perform the following operations in order:
1. Add "cherry" and "date" to the end of the array.
2. Remove the last element from the array.
3. Add "grape" to the beginning of the array.
4. Remove the first element from the array.
5. Finally, print the modified array. What is the expected
output?
Takeaway question 2
⚫ What will be the output of the following PHP code?
1. $numbers = [10, 20, 30];
2. array_push($numbers, 40);
3. array_unshift($numbers,5);
4. array_pop($numbers);
5. array_shift($numbers);
6. array_push($numbers, 50);
7. array_unshift($numbers, 1);
8. print_r($numbers);
Adding and Removing array elements
⚫ array_pad()
⚫ The array_pad() function is used to expand an array to a
specified length by adding a specified value either at the
beginning or the end.
⚫ Syntax: array_pad($array, $size, $value)
⚫ $array – The original array.
⚫ $size – The desired total length of the array:
⚫ If $size is positive, padding is added to the end of the array.
⚫ If $size is negative, padding is added to the beginning of the
array.
⚫ $value – The value used for padding.
Adding and Removing array elements
⚫ array_pad()
⚫ The array_pad() function modifies the target array,
increasing its size to the length specified by length.
Locating array elements
⚫ Array_keys()
⚫ returns an array consisting of all keys located in the array
target array.
⚫ Syntax: array_keys($array, $search_value, $strict)
⚫ $array – The input array.
⚫ $search_value (optional) – If provided, array_keys() will
return only the keys of elements matching this value.
⚫ $strict (optional) – If true, it will use strict comparison (===)
when searching for values.
⚫ array_keys() does not modify the original array. It only
returns a new array containing all the keys from the original
array.
Locating array elements
⚫ Array_keys()
⚫ array_keys($array, $search_value, $strict)
Locating array elements
⚫ array_key_exists()
⚫ returns TRUE if the supplied key is found in the array
target_array, and returns FALSE otherwise.
⚫ $fruits= ["a" => "Apple", "b" => "Banana", "c" => "Cherry"];
⚫ array_key_exists($keyToCheck, $arrayName);
⚫ array_key_exists(“b”, $fruits); //1
Locating array elements
⚫ array_values()
⚫ The array_values() function returns all values located in the
target array, automatically providing numeric indexes for the
returned array.
⚫ array_values() returns a new indexed array containing all the
values from the original array
Locating array elements
⚫ array_search()
⚫ searches the array for a given value and returns the first
corresponding key if successful
⚫ Syntax: array_search($needle, $haystack, $strict)
⚫ $needle – The value to search for
⚫ $haystack – The array to search in
⚫ $strict (optional) – If true, the search will use strict
comparison (===)
⚫ $key = array_search("Banana", $ assocArray);
Takeaway questions
⚫ Given the array, $data = ["a" => 10, "b" => 20, "c" => 30];
1. Extend it to 5 elements, filling new slots with 0;
2. What will be the output of array_keys($data)?
3. Write a PHP condition to check if "b" exists as a key in
$data.
4. What will be the output of array_values($data)?
5. Write a PHP statement to find the key of 30 in $data.
Traversing array
⚫ Using foreach loop ⚫ $person = ["name" =>
⚫ $colors=[“blue”,”yellow”,”r "Alice", "age" => 25, "city" =>
ed”]; "New York"];
⚫ foreach ($colors as $value) ⚫ foreach ($person as $key
⚫ { => $value)
⚫ echo "$value <br>"; ⚫ {
⚫ } ⚫ echo "$key: $value\n";
⚫ }
Determine Array size and uniqueness
⚫ count()
⚫ count(input_array)
⚫ returns the total number of values found in the input_array.
⚫ Sizeof() function can be also used.
⚫ array_count_values()
⚫ returns an array consisting of associative key/value pairs.
⚫ Each key represents a value found in the input_array, and its
corresponding value denotes the frequency of that key’s
appearance (as a value) in the input_array.
⚫ E.g. $states = ["Ohio", "Iowa", "Ohio", "Arizona", "Iowa"];
⚫ $countedValues = array_count_values($states)
//output: Array ( [Ohio] => 2 [Iowa] => 2 [Arizona] => 1 )
Sorting Array
⚫ sort()
⚫ sorts the target_array, ordering elements from lowest to highest
value.
⚫ rsort()
⚫ is identical to sort(), except that it sorts array items in reverse
(descending) order.
⚫ asort()
⚫ is identical to sort(), sorting the target_array in ascending order,
except that the key/value correspondence is maintained.
⚫ ksort()
⚫ sorts the input array array by its keys, returning TRUE on success
and FALSE otherwise.
⚫ krsort()
⚫ operates identically to ksort(), sorting by key, except that it sorts in
Merging, Slicing, splicing and Dissecting
⚫ array_combine()
⚫ array array_combine(array keys, array values)
⚫ produces a new array consisting of keys residing in
the input parameter array keys, and corresponding
values found in the input parameter array values.
⚫ both input arrays must be of equal size, and that
neither can be empty.
⚫ E.g. $abbreviations = array("AL","AK","AZ","AR");
⚫ $states = array("Alabama","Alaska","Arizona","Arkansas");
⚫ $stateMap = array_combine($abbreviations,$states);
Merging, Slicing, Splicing and Dissecting
⚫ array_merge()
⚫ function used to merge two or more arrays into one.
⚫ Syntax: array_merge(...$arrays)
⚫ If an input array contains a string key that already
exists in the resulting array, that key/value pair will
overwrite the previously existing entry.
Merging, Slicing, splicing and Dissecting
⚫ array_slice()
⚫ Syntax: array_slice($array, $offset, $length,
$preserve_keys)
⚫ Returns an extracted portion of an array while
preserving the keys (if preserve_keys is set to true)
⚫ $array – The input array.
⚫ $offset – The starting index (0-based). A negative value
counts from the end.
⚫ $length (optional) – The number of elements to extract.
If omitted, it extracts till the end.
⚫ $preserve_keys (optional, default: false) – Whether to
preserve original keys (true) or reindex them (false).
Merging, Slicing, splicing and Dissecting
⚫ array_slice()
⚫ Syntax: array_slice($array, $offset, $length,
$preserve_keys)
Merging, Slicing, splicing and Dissecting
⚫ array_splice()
⚫ is used to remove, replace, or insert elements in an array.
Unlike array_slice(), it modifies the original array.
⚫ Syntax: array_splice(&$array, $offset, $length,
$replacement)
⚫ $array (by reference) – The input array that will be modified.
⚫ $offset – The starting index (0-based). A negative value counts
from the end.
⚫ $length (optional) – The number of elements to remove. If
omitted, it removes all elements from $offset onward.
⚫ $replacement (optional) – If provided, these values replace
the removed elements.
Merging, Slicing, splicing and Dissecting
⚫ array_splice()
⚫ Syntax: array_splice(&$array, $offset, $length,
$replacement)
⚫ Example (removing elements)
Merging, Slicing, splicing and Dissecting
⚫ array_splice()
⚫ Syntax: array_splice(&$array, $offset, $length,
$replacement)
⚫ Example (replacing elements)
Merging, Slicing, splicing and Dissecting
⚫ array_splice()
⚫ Syntax: array_splice(&$array, $offset, $length,
$replacement)
⚫ Example (inserting elements without removing)
Merging, Slicing, splicing and Dissecting
⚫ array_intersect() is used to find common values between
two or more arrays. It returns an array containing all the
values that exist in all the input arrays
End of chapter 1