2️⃣
Php & MySql: Module II
Creating arrays (associative &
multidimensional)
Associative Arrays
An associative array in PHP is an array that uses named keys rather than
numerical indices to access values. Each element in the array is a key-value
pair, where the key is a string and the value can be of any data type.
Explanation:
Associative array structure:
array {
key1 => value1,
key2 => value2,
key3 => value3,
...
}
Example
// Creating an associative array
$person = array(
'name' => 'John',
'age' => 25,
'city' => 'New York'
);
// Accessing values
echo $person['name']; // Output: John
echo $person['age']; // Output: 25
echo $person['city']; // Output: New York
Php & MySql: Module II 1
Multidimensional Arrays
A multidimensional array is an array that contains one or more arrays as its
elements. In PHP, you can create arrays of arrays, forming a matrix-like
structure.
Explanation:
Multidimensional array structure:
array(
array(
'key1' => 'value1',
'key2' => 'value2',
// ... more key-value pairs
),
array(
'key1' => 'value1',
'key2' => 'value2',
// ... more key-value pairs
),
// ... more arrays
);
or
[
[value11, value12, value13, ...],
[value21, value22, value23, ...],
[value31, value32, value33, ...],
...
]
Example 1: Using array() Function
<?php
// Example using array() function
$employees_array_function = array(
array(
'name' => 'Alice',
'age' => 30,
'department' => 'HR'
),
array(
Php & MySql: Module II 2
'name' => 'Bob',
'age' => 28,
'department' => 'IT'
),
array(
'name' => 'Charlie',
'age' => 35,
'department' => 'Finance'
)
);
// Output the multidimensional array
print_r($employees_array_function);
Example 2: Using Short Array Syntax ( [] )
<?php
// Example using short array syntax
$employees_short_syntax = [
[
'name' => 'Alice',
'age' => 30,
'department' => 'HR'
],
[
'name' => 'Bob',
'age' => 28,
'department' => 'IT'
],
[
'name' => 'Charlie',
'age' => 35,
'department' => 'Finance'
]
];
// Output the multidimensional array
print_r($employees_short_syntax);
Array related functions
1. Count and Sizeof:
count($array) and sizeof($array) both return the number of elements in
an array.
Example: $count = count($colors); (Returns 4)
Php & MySql: Module II 3
$colors = array("blue", "black", "red", "green");
// Both count() and sizeof() return 4
$count = count($colors);
$size = sizeof($colors);
echo "Count: $count, Size: $size";
2. Each and List:
each()and list() are used together to step through an array, returning
keys and values.
$colors = array("blue", "black", "red", "green");
while ($color = each($colors)) {
list($key, $value) = $color;
echo "Key: $key, Value: $value\n";
}
3. Foreach:
foreach($array as $key => $value) is a control structure for iterating through
an array.
$numbers = array(1, 2, 3, 4, 5);
foreach ($numbers as $number) {
echo $number . " ";
}
// Output: 1 2 3 4 5
4. Reset:
reset($array) rewinds the pointer to the beginning of an array.
$characters = array("A", "B", "C");
// Reset the pointer to the beginning
reset($characters);
echo current($characters); // Output: A
5. Array Push and Array Pop:
Php & MySql: Module II 4
array_push($array, $element1, $element2, ...) adds elements to the end of
an array.
array_pop($array) removes and returns the last element of an array.
$stack = array();
// Adding elements to the end
array_push($stack, "element1", "element2", "element3");
// Removing and getting the last element
$lastElement = array_pop($stack);
echo "Last Element: $lastElement\n";
6. Array Unshift and Array shift:
array_unshift($array, $element1, $element2, ...) adds elements to the
beginning of an array.
array_shift($array) removes and returns the first element of an array.
$queue = array();
// Adding elements to the beginning
array_unshift($queue, "element1", "element2", "element3");
// Removing and getting the first element
$firstElement = array_shift($queue);
echo "First Element: $firstElement\n";
7. Array Merge:
array_merge($array1, $array2, ...) combines two or more arrays.
$array1 = array("a", "b");
$array2 = array(1, 2);
$newArray = array_merge($array1, $array2);
print_r($newArray);
// Output: Array ( [0] => a [1] => b [2] => 1 [3] => 2 )
Php & MySql: Module II 5
8. Array Keys and Array Values:
array_keys($array) returns an array containing all the key names within a
given array.
array_values($array) returns an array containing all the values within a
given array.
$person = array("name" => "John", "age" => 25, "city" => "New York");
// Get keys
$keys = array_keys($person);
print_r($keys);
// Get values
$values = array_values($person);
print_r($values);
9. Shuffle:
shuffle($array) randomizes the elements of a given array.
$deck = range(1, 52); // Create an array with values from 1 to 52
shuffle($deck);
print_r($deck); // Output: Randomized array
Working with string functions
Formatting Strings with PHP
Printf()
The printf() function in PHP is a powerful tool for formatting strings. It
allows you to create well-structured and visually appealing output by
specifying the format of the output string and inserting variables into it. The
format string contains placeholders, known as conversion specifications,
which define how the variables should be displayed.
<?php
$name = "Alice";
$age = 25;
printf("Name: %s, Age: %d", $name, $age);
Php & MySql: Module II 6
// Output: Name: Alice, Age: 25
?>
Type Specifiers
Type specifiers determine the type of the variable being inserted into the
format string. Common type specifiers include:
%s : String
%d or %i : Integer
%f : Float
%b : Binary
%x or %X : Hexadecimal
$name = "John";
$age = 25;
printf("Name: %s, Age: %d", $name, $age);
// Output: Name: John, Age: 25
Padding Specifiers
Padding specifiers allow you to control the width of the field and add
padding to align values. The syntax is %[flags][width]specifier .
• Flags: - (left-justify), + (forces a sign), 0 (pad with zeros)
$number = 42;
printf("%05d", $number);
// Output: 00042
Specifying Field Width
You can set the minimum width of the field to ensure consistent formatting.
This is useful for aligning values.
$price = 19.99;
printf("Price: $%8.2f", $price);
// Output: Price: $ 19.99
Php & MySql: Module II 7
Specifying Precision
For floating-point numbers, precision controls the number of digits after the
decimal point.
$pi = 3.14159;
printf("%.2f", $pi);
// Output: 3.14
Argument Swapping
You can change the order of the arguments in the printf() function by
specifying the argument number.
$name = "Bob";
$age = 30;
printf("Age: %2$d, Name: %1$s", $name, $age);
// Output: Age: 30, Name: Bob
Storing a Formatted String
If you want to store the formatted string instead of printing it, you can use
the sprintf() function.
$name = "Eva";
$age = 22;
$formattedString = sprintf("User: %s, Age: %d", $name, $age);
// $formattedString now holds the formatted string
Using Date and Time Functions
date()
The date() function is used to format the current date and time or a
specified timestamp according to a specified format.
syntax
Php & MySql: Module II 8
string date ( string $format ,$timestamp)
$format : Required. The format of the outputted date string.
$timestamp : Optional. The timestamp to be formatted. If not provided,
the current timestamp from time() is used.
Example
<?php
// Get the current date and time
$currentDateTime = date("Y-m-d H:i:s");
echo "Current Date and Time: $currentDateTime";
// Get the current date
$currentDate = date("Y-m-d");
echo "Current Date: $currentDate";
// Get the current time
$currentTime = date("H:i:s");
echo "Current Time: $currentTime";
?>
time()
The time() function returns the current Unix timestamp, which is the
number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
syntax
int time ( void )
Example
<?php
// Get the current timestamp
$currentTimestamp = time();
echo "Current Timestamp: $currentTimestamp";
?>
Php & MySql: Module II 9