Skip to content

Commit 63a57c6

Browse files
finish procedural php project
1 parent 77b0063 commit 63a57c6

File tree

13 files changed

+336
-39
lines changed

13 files changed

+336
-39
lines changed

01-Basic.php

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@
22
/*== 1. Environment Setup ==*/
33
// Web Server: Client - Server (Hardware) - Web Server (Apache/Nginx Software)
44
// Ways to Install: Manual Installationin and Configuration in OS, XAMPP type Server(Preconfigured, Cant Run Multiple Version of PHP or Database, Not For Production), Virtual Machine/Docker (Better Alternative)
5-
// Run PHP Script in Command Line: cd directory - php index.php
5+
// Run PHP Script in Command Line: cd directory -> php index.php
66

77
/*== 2. Basic Syntax ==*/
88
echo 'PHP Print'; // If close php here, no need semicolon
99
echo 'PHP', '', 'Print'; // Same Output as Above
1010
print 'PHP Print'; // Print has a return value 1, same Output of Echo
1111
echo print "PHP Print"; // Output: PHP Print1 , added 1 at last
1212
// Print could be used in expression like if(print()), echo cant: print echo will not work
13-
print('PHP Print'); // Same as print
1413
echo 'Abdul\'s'; // Escaping Quotes
15-
echo "Abdul's"; // Escaping Quotes
14+
echo "OK\"Nothing\\\\Tata\'\$"; // Escaping Characters
15+
$path = 'C:\\Program Files\\Test';
1616
$printR = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); // To Test
1717
print_r($printR); // Print Array in Human Readable Way
1818
// Not So Much Used: printf()- with format specifier like c programming, sprintf()
@@ -40,7 +40,7 @@
4040
$fname = 'Abdul';
4141
$lname = 'Alim';
4242
printf('Full Name: %2$s %1$s', $lname, $fname);
43-
echo "\n";
43+
echo "\n"; // Line Break
4444
// Variable Variables (Create Variable Dynamically)
4545
$foo = bar;
4646
$$foo = baz; // $$foo actually means $bar
@@ -65,7 +65,7 @@
6565
echo PI; // Output: 3.14
6666
echo defined('PI'); // Output: 1, checking if any constant defined
6767
const STATUS_PAID = 'paid'; // Define constant using const keyword, will define at compile time.
68-
// So, we cant use const in controlled structure like loopor if-else, but can use define() in controlled structure
68+
// So, we cant use const into controlled structure like loop or if-else, but can use define() in controlled structure
6969
// When static data, can use const. When dynamic data, can use define(). Ex-
7070
define('STATUS_' . $x, 4);
7171
echo STATUS_1;
@@ -74,7 +74,8 @@
7474
// __TRAIT__, __METHOD__, __NAMESPACE__
7575

7676
/*== 5. Data Types and Type Casting ==*/
77-
// Scalar Types: bool, int, float, string
77+
// Scalar Types: bool, int, float, string, has no dedicated 'double' but if we check float using gttype() it will show
78+
// double, because float and double same in php
7879
// Compound Types: array, object, callable, iterable
7980
// Special Types: resource, null. Scalar and Special types are primitive data types
8081
// Checking Type: gettype($var)- Only Data Type, var_dump($var) - Data Type with Value
@@ -102,7 +103,7 @@ function sum(int $x, int $y){
102103
// 05 will output to 5, 055 will output to 45. It is taking as octal
103104
// Prefix for Binary: 0b. 0b110 = 6
104105
$testInt2 = PHP_INT_MAX + 1; // When Maximum limit exceeds, it will auto converted to float
105-
// Casting: (int) or (integer)
106+
// Casting: (int) or (integer) or +$var
106107
$testInt2 = (int) 5.98; // Output: 5 (rounded auto, point will get removed)
107108
$testInt3 = (int) '5ABC'; // Output: 5
108109
$testInt4 = (int) 'ABC'; // Output: 0. Also null and false will be 0
@@ -111,30 +112,31 @@ function sum(int $x, int $y){
111112
is_int($testInt);
112113

113114
/*== 7. Float Data Type: Positive or Negative Numbers with Decimal Points ==*/
114-
$testFloat = 13.5e3; // Output: 13500
115+
$testFloat = 13.5e3; // Output: 13500, floating-point number in scientific notation, equivalent to 13.5 × 10³
115116
$testFloat2 = 13.5e-3; // Output: 0.0135
116117
// Can use Underscore like Integer. PHP_FLOAT_MAX, PHP_FLOAT_MIN
117118
echo NAN; // Output: NAN, when calculation cant be done
118119
echo log(-1); // Output: NAN
119120
echo PHP_FLOAT_MAX * 2; // Output: INF (infinity)
120-
// Check: is_infinite(), is_finite(), is_nan()
121+
// Check: is_infinite(), is_finite(), is_nan(), is_float
121122
// Casting: (float), (floatval)
122123

123124
/*== 7. Null(constant) Data Type: null or NULL ==*/
124125
// When null casted to string, it will empty string
125126
// Check: is_null or use ===
126127
// If variable not defined, it will throgh error but will get null
127-
// Cat to int: 0, to arrayL [], boolean: false
128+
// Cast to int: 0, to array: [], boolean: false
128129

129130
/*== 8. Expression and Operators ==*/
130131
#Arithmetic Operator: + - * / % **
131132
$number = '10'; // string
132133
var_dump(+$number); // for having + operator, it will cast to integer
133-
var_dump(fdiv(10, 0)); // Output: 10 % 0- Infinity, if fdiv not used throgh error for dividing by 0
134+
var_dump(fdiv(10, 0)); // Output: 10 % 0- Infinity, if fdiv not used throgh error for 10 / 0
134135
// fmod(10, -3) , Output: 1 (10 % 3). Use when mod of floating number
135-
#Assignment IOperator: = += +- *- /= %= **=
136+
// fdiv and fmod works on floating point numbers to divide and modulus
137+
#Assignment Operator: = += +- *- /= %= **=
136138
#String Operator: . .=
137-
#Comparisn Operator: loose comparisn, strick comparisn, spaceship operator, conditional/ternary etc
139+
#Comparisn Operator: loose comparisn, strct comparisn, spaceship operator, conditional/ternary etc
138140
#Error Control Operator (@): Not Recommened to Use
139141
$errorControl = @file('foo.txt'); // As file not present it should throgh error, but it will not
140142
# Increment Decrement Operator (++ , --)
@@ -147,8 +149,8 @@ function sum(int $x, int $y){
147149
# (+ == === !== <> !===) Array Operators
148150
# Execution Operators
149151
# Type Operator (instanceof)
150-
# Nullsafe Operator (?)
151-
152+
# Nullsafe Operator (??)
153+
# Ternary Operator
152154
# Operator Precedence and Associativity
153155

154156
/*== 9. String Data Type: When in Quote ==*/
@@ -157,7 +159,7 @@ function sum(int $x, int $y){
157159
echo $lastName;
158160
echo $firstName[0]; // Output: A
159161
$firstName[-2] = ''; // Converted to: Abul
160-
// Declaration by Heredoc (treats that it is in double quote)
161-
// $stringTest = three less than TEXT Line1 Lin2 TEXT; echo nl2br($stringTest). Use Case: like pre tag
162+
// Declaration by Heredoc (treats that it is in double quote). Use Case: like pre tag, consider all white space
163+
// $stringTest = three less than TEXT Line1 Lin2 TEXT; echo nl2br($stringTest).
162164
// Declaration by Nowdoc:
163165
//(treats that it is in single quote): three less than 'TEXT' - same just use sigle quote . Any space will render.
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
function getTransactionFiles(string $dirPath): array{
6+
$file = [];
7+
8+
foreach(scandir($dirPath) as $file){
9+
if(is_dir($file)){
10+
continue; // Exclude Folder Dir, Just Take File
11+
}
12+
$files[] = $dirPath . $file;
13+
}
14+
return $files;
15+
}
16+
17+
function getTransactions(string $fileName, ?callable $transactionHandler = null): array{
18+
if(! file_exists($fileName)){
19+
trigger_error('File ' . $fileName . ' does not exist', E_USER_ERROR);
20+
}
21+
22+
$file = fopen($fileName, 'r');
23+
fgetcsv($file); // Exclude the Header, First Line
24+
25+
$transactions = [];
26+
27+
while(($transaction = fgetcsv($file)) !== false){
28+
if($transactionHandler !== null){
29+
$transaction = $transactionHandler($transaction);
30+
} // Here, we will use extractTransaction(). But we can have different row format in another file, so for flexibility, we took this formatting method as callback argument
31+
$transactions[] = $transaction;
32+
}
33+
return $transactions;
34+
}
35+
36+
function extractTransaction(array $transactionRow): array{
37+
[$date, $checkNumber, $description, $amount] = $transactionRow;
38+
$amount = (float) str_replace(['$', ','], '', $amount);
39+
40+
return [
41+
'date' => $date,
42+
'checkNumber' => $checkNumber,
43+
'description' => $description,
44+
'amount' => $amount,
45+
];
46+
}
47+
48+
function calculateTotals(array $transactions): array{
49+
$totals = ['netTotal' => 0, 'totalIncome' => 0, 'totalExpense' => 0];
50+
foreach($transactions as $transaction){
51+
$totals['netTotal'] += $transaction['amount'];
52+
53+
if($transaction['amount'] >= 0){
54+
$totals['totalIncome'] += $transaction['amount'];
55+
}
56+
else{
57+
$totals['totalExpense'] += $transaction['amount'];
58+
}
59+
}
60+
// we can use array_reduce or array_sum but it will get less performance
61+
return $totals;
62+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
function formatDollarAmount(float $amount): string{
5+
$isNegative = $amount < 0;
6+
return ($isNegative ? '-' : '') . '$' . number_format(abs($amount), 2);
7+
}
8+
9+
function formatDate(string $date): string{
10+
return date('M j, Y', strtotime($date));
11+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types = 1); // strictly enforce types in function calls
4+
5+
$root = dirname(__DIR__) . DIRECTORY_SEPARATOR;
6+
// dirname(__DIR__): Parent Directory of the Directory where current file Located (One Level Up from Current Directory)
7+
// DIRECTORY_SEPARATOR: / on Linux/macOS or \ on Windows, platform-independent code
8+
9+
define('APP_PATH', $root . 'app' . DIRECTORY_SEPARATOR); // Creates Constant APP_PATH - ./app/
10+
define('FILES_PATH', $root . 'transaction_files' . DIRECTORY_SEPARATOR);
11+
define('VIEWS_PATH', $root . 'views' . DIRECTORY_SEPARATOR);
12+
13+
require APP_PATH . 'App.php';
14+
require APP_PATH . 'helpers.php';
15+
16+
$files = getTransactionFiles(FILES_PATH);
17+
18+
$transactions = [];
19+
foreach($files as $file){
20+
$transactions = array_merge($transactions, getTransactions($file, 'extractTransaction'));
21+
}
22+
23+
$totals = calculateTotals($transactions);
24+
25+
require VIEWS_PATH . 'transactions.php';
26+
// Now, $transactions varible will be available within the view file
63.6 KB
Loading
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
Date,Check #,Description,Amount
2+
01/04/2021,7777,Transaction 1,"$150.43"
3+
01/05/2021,,Transaction 2,"$700.25"
4+
01/06/2021,,Transaction 3,"-$1,303.97"
5+
01/07/2021,,Transaction 4,"$46.78"
6+
01/08/2021,,Transaction 5,"$816.87"
7+
01/11/2021,1934,Transaction 6,"-$1,002.53"
8+
01/12/2021,7307,Transaction 7,"$532.22"
9+
01/13/2021,1352,Transaction 8,"-$704.59"
10+
01/14/2021,,Transaction 9,"$98.04"
11+
01/15/2021,,Transaction 10,"-$204.56"
12+
01/25/2021,,Transaction 11,"$1,056.27"
13+
01/26/2021,,Transaction 12,"$550.10"
14+
01/27/2021,,Transaction 13,"-$825.77"
15+
01/28/2021,4250,Transaction 14,"$212.68"
16+
01/29/2021,,Transaction 15,"$195.68"
17+
02/02/2021,9915,Transaction 16,"-$463.75"
18+
02/03/2021,,Transaction 17,"$78.02"
19+
02/04/2021,,Transaction 18,"$268.81"
20+
02/05/2021,,Transaction 19,"$1,360.55"
21+
02/08/2021,,Transaction 20,"-$594.46"
22+
02/09/2021,9125,Transaction 21,"$467.39"
23+
02/10/2021,,Transaction 22,"$39.49"
24+
02/11/2021,7929,Transaction 23,"-$81.87"
25+
02/12/2021,,Transaction 24,"$255.64"
26+
02/12/2021,,Transaction 25,"$13.51"
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
<!DOCTYPE html>
2+
<html>
3+
4+
<head>
5+
<title>Transactions</title>
6+
<style>
7+
table {
8+
width: 100%;
9+
border-collapse: collapse;
10+
text-align: center;
11+
}
12+
13+
table tr th,
14+
table tr td {
15+
padding: 5px;
16+
border: 1px #eee solid;
17+
}
18+
19+
tfoot tr th,
20+
tfoot tr td {
21+
font-size: 20px;
22+
}
23+
24+
tfoot tr th {
25+
text-align: right;
26+
}
27+
</style>
28+
</head>
29+
30+
<body>
31+
<table>
32+
<thead>
33+
<tr>
34+
<th>Date</th>
35+
<th>Check #</th>
36+
<th>Description</th>
37+
<th>Amount</th>
38+
</tr>
39+
</thead>
40+
<tbody>
41+
<?php if(! empty($transactions)): ?>
42+
<?php foreach($transactions as $transaction): ?>
43+
<tr>
44+
<td><?= formatDate($transaction['date']) ?></td>
45+
<td><?= $transaction['checkNumber'] ?></td>
46+
<td><?= $transaction['description'] ?></td>
47+
<td>
48+
<?php if($transaction['amount'] < 0): ?>
49+
<span style="color: red;">
50+
<?= $transaction['amount'] ?>
51+
</span>
52+
<?php elseif($transaction['amount'] > 0): ?>
53+
<span style="color: green;">
54+
<?= $transaction['amount'] ?>
55+
</span>
56+
<?php else: ?>
57+
<?= $transaction['amount'] ?>
58+
<?php endif ?>
59+
</td>
60+
</tr>
61+
<?php endforeach ?>
62+
<?php endif ?>
63+
</tbody>
64+
<tfoot>
65+
<tr>
66+
<th colspan="3">Total Income:</th>
67+
<td><?= formatDollarAmount($totals['totalIncome']) ?? 0 ?></td>
68+
</tr>
69+
<tr>
70+
<th colspan="3">Total Expense:</th>
71+
<td><?= formatDollarAmount($totals['totalExpense']) ?? 0 ?></td>
72+
</tr>
73+
<tr>
74+
<th colspan="3">Net Total:</th>
75+
<td><?= formatDollarAmount($totals['netTotal']) ?? 0 ?></td>
76+
</tr>
77+
</tfoot>
78+
</table>
79+
</body>
80+
81+
</html>

02-Array.php

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<?php
2-
/*== 1. Array Declaration ==*/
2+
/*== 1. Array Declaration and Checking ==*/
33
$array1 = [1, 2, 3];
44
$array2 = array(1, 2, 3);
55
echo $array1[1]; // Output: 2 (at index 1)
@@ -18,6 +18,12 @@
1818
$newKey = 'Javascript';
1919
$array[$newKey] = 'ES6'; // Pushed a New Key Value into Array Dynamically
2020

21+
$firstname = "Peter";
22+
$lastname = "Griffin";
23+
$age = "41";
24+
$result = compact("firstname", "lastname", "age"); // Create array containing variables and their values
25+
$number = range(0,5); // Creates array from 0 to 5
26+
2127
$array4 = [0 => 'foo', 1 => 'bar', '1' => 'baz']; // Index 1's value will be baz, becaue it is overrode
2228
$array5 = [true => 'a', 1 => 'b', '1' => 'c', 1.8 => 'd', null => 'e'];
2329
print_r($array5); // Output: 1 => d, [] => e.
@@ -33,25 +39,20 @@
3339
var_dump((array) $x); // Array Casting. Output: 0 => 3.
3440
// Null will be an empty array if casted
3541

36-
$firstname = "Peter";
37-
$lastname = "Griffin";
38-
$age = "41";
39-
$result = compact("firstname", "lastname", "age"); // Create array containing variables and their values
40-
$number = range(0,5); // Creates array from 0 to 5
41-
4242
/*== 1. Array Functions ==*/
4343
$items = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
44-
echo count($items); // Length of the Array
44+
echo count($items); // Length of the Array, or sizeof()
4545
array_push($array2, 4, 5); // Push as Last Items. Pass by Reference, It changed the original array
4646
array_pop($items); // Remove Last Element
4747
array_shift($items); // Remove First Element
48+
array_unshift($items, 4); // Add at first
4849
// After Removing, index will be reindexing auto. for array6, if we remove, then indexing will automatic not 50
4950
// But rather than 50, if it was a string, it will not be re-indexed
5051
// But, unset() dont reindex if we destroy any key using it
5152
array_key_exists('a', $items); // Check if key exists in an array
5253
array_chunk($items, 2); // Array will be divided, 0 => [0 => 1, 1 => 2], 1 => []...
5354
array_chunk($items, 2, true); // Key will be reserved, 0 => [a => 1, b => 2], 1 => []...
54-
array_combine($array1, $array2); // First Array's Value will be Key, Second's will be Value. Length must be same.
55+
array_combine($array1, $array2); // First Array's Value will be Key, Second's value will be Value. Length must be same.
5556
$even = array_filter($aray1, fn($number) => $number % 2 === 0); // $number performs filter operation on value and new array return
5657
$even2 = array_filter($aray1, fn($number) => $number % 2 === 0, ARRAY_FILTER_USE_KEY); // Now $number argument performs operation on key
5758
$even3 = array_filter($aray1, fn($number, $key) => $number % 2 === 0, ARRAY_FILTER_USE_BOTH); // Can use both key and value now
@@ -90,7 +91,7 @@
9091
// usort Remove Custom Keys, and Use Numeric Keys Instead
9192

9293
// Array Destructuring (De structure array into separate variables)
93-
list($a, $b, $c) = $array1; // or, shorter version
94+
list($a, $b, $c) = $array1; // or, shorter version:
9495
[$a, $b, $c] = $array1;
9596
[$a, , $c] = $array1; // 2nd element is skipped
9697
// Destructing can be from nested array also: [$a, $b , [$c, $d]]
@@ -128,7 +129,7 @@
128129
// array_splice() Removes and replaces specified elements of an array
129130
// array_sum() Returns the sum of the values in an array
130131
// array_unique() Removes duplicate values from an array
131-
// array_walk() Applies a user function to every member of an array
132+
// array_walk() Applies a user function to every member of an array, but on single array and change original array, no return value
132133
// current() Returns the current element in an array
133134
// end() Sets the internal pointer of an array to its last element
134135
// extract() Imports variables into the current symbol table from an array

0 commit comments

Comments
 (0)