# PHP
> [TOC]
:::info
[Cheatsheet](https://www.codecademy.com/learn/learn-php/modules/getting-started-with-php/cheatsheet)
:::
## History
* 1994
* Containing built-in functionality for interacting with web data
* Can be used on its own to create web application back-ends
* Provide underlying code
* content management systems (CMS)
* Allowing users to create and update websites without having write a lot of complex code themselves
* WordPress, Drupal, Joomla
* e-commerce platforms
* PHP framworks
* Laravel, CakePHP, Symfony
## How is PHP used in HTML?
* PHP is often used to build dynamic web pages
* ```
<?php
?>
```
* `echo "hello";`
> An instruction written in PHP is called a **statement**
## How is PHP executed?
* Can also be executed from the terminal
* PHP ignores **whitespace (tabs, spaces, new lines)**
## Some syntax
### comments
* `#`
* `//`, `/* */`
<!--```htmlmixed=
<?php
require 'vendor/autoload.php';
# This logic handles connecting to the database, where we store our todo status
$pdo = new \PDO("sqlite:" . "db/sqlite.db");
# This PHP logic handles user actions
# New TODO
if (isset($_POST['submit']))
{
$description = $_POST['description'];
$sth = $pdo->prepare("INSERT INTO todos (description) VALUES (:description)");
$sth->bindValue(':description', $description, PDO::PARAM_STR);
$sth->execute();
}
# Delete TODO
elseif (isset($_POST['delete']))
{
$id = $_POST['id'];
$sth = $pdo->prepare("delete from todos where id = :id");
$sth->bindValue(':id', $id, PDO::PARAM_INT);
$sth->execute();
}
# Update completion status
elseif (isset($_POST['complete']))
{
$id = $_POST['id'];
$sth = $pdo->prepare("UPDATE todos SET complete = 1 where id = :id");
$sth->bindValue(':id', $id, PDO::PARAM_INT);
$sth->execute();
}
# Here is the HTML:
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Todo List</title>
</head>
<body class="container">
<h1>Todo List</h1>
<form method="post" action="">
<input type="text" name="description" value="">
<input type="submit" name="submit" value="Add">
</form>
<h2>Current Todos</h2>
<table class="table table-striped">
<thead><th>Task</th><th></th><th></th></thead>
<tbody>
<?php
# Entering PHP mode,
$sth = $pdo->prepare("SELECT * FROM todos ORDER BY id DESC");
$sth->execute();
foreach ($sth as $row) {
# Exiting PHP Mode
?>
<tr>
<td>
<!-- This is PHP shorthand for inserting dynamic text into HTML -->
<?=htmlspecialchars($row['description'])?></td>
<td>
<?php # Here we are mixing HTML and PHP to get the desired document
if (!$row['complete']) {
?>
<form method="POST">
<button type="submit" name="complete">Complete</button>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="hidden" name="complete" value="true">
</form>
<?php
} else {
?>
Task Complete!
<?php
}
?>
</td>
<td>
<form method="POST">
<button type="submit" name="delete">Delete</button>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="hidden" name="delete" value="true">
</form>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
```-->
## Strings and Variables
### Strings
> [php docs](https://www.php.net/manual/en/language.types.string.php)
* `\`
* 跳脫字元
* `\n`
* 換行
* Concatenation
* `.`
* `echo "one" . "two";` -> onetwo
### declaration
* `$example = "wwwwww";`
```php=
<?php
$noun = "dog";
$adj = "cute";
echo "I love ${noun}s, they are so $adj.";
// I love dogs, they are so cute.
```
* `.=`
* `$ex .= " hi"`
* `=&`
* assign by reference
* 會動到原本的值
### Numbers
* `echo 1+2-3*7/1%2;`
* `**`
* 次方
* `+=`, `-=`, `*=`, `/=`, `%=`
* `++`, `--`
## functions
```php=
$bla = "bla";
function myFunciton($a, $b = 100, &$c){
global $bla;
}
```
* `echo`
* `echo("This would work". "\n");`
* `echo "This", " ", "also.", "\n";`
* `strrev(string)`
* return reverse the string
* `strtolower(string)`
* `str_repeat(str, times)`
* `substr_count(string, string)`
* `abs(num)`
* `round(num)`
* return nearest integer
* `rand()`
* `getrandmax()`
> 2147483647
### Doc
* abs ( mixed $number ) : number
> `ads`: fun-name
> `mixed`: because there are multiple data types the function will accept (an integer or a float)
> `$number`: parameter name
> `:number`: the data type the function will return (Here is the `number`)
>
## Array
* `$my_array = array(0, 1, 2);`
* `$number_array = [0, 1, 2];`
* PHP arrays can also store elements of multiple data types
* `count($arr)`
* number of elements in arr
### print arr
* `implode($glue, $message);`
* ex. `$message = ["PHP", 1, "bla"];`
* -> `echo implode("!", $message)`
> PHP!1!bla!
* `print_r($message);`
> Array
(
[0] => “PHP”
[1] => 1
[2] => “bla”
)
### element operation
* `$string_array = ["first element", "second element"];`
* **`$string_array[] = "third element";`**
* $string_array = ["first element", "second element",
"third element"]
* `arr_push(arr, val);`
* push from back
* `arr_pop(arr);`
* pop from back
* `arr_unshift(arr, val);`
* push from front
* `arr_shift(arr);`
* pop from front
### key - value
* create
```php=
$about_me = array(
"fullname" => "Aisle Nevertell",
"social" => 123456789,
8787878 => "87"
);
```
* 修改值
```php=
$about_me["social"] = 0;
```
* `unset($about_me["fullname"]);`
* delete `["fullname"]`
## Front-End
## PHP with HTMl
* `<?php echo "hi";?>` = `<?="hi";?>`
* front end client **makes a request** to a backend PHP server, several **superglobals related to the request** are available to the PHP script
* `$GLOBALS`
* `$_SERVER`
* `$_GET`
* contains an associative array of variables passed to the current script using query parameters in the URL
* `$_POST`
* contains an associative array of variables passed to the current script using a form submitted using the “POST” method
* `$_FILES`
* `$_COOKIE`
* `$_SESSION`
* `$_REQUEST`
* contains the contents of `$_GET`, `$_POST`, and `$_COOKIE`
* `$_ENV`
## Form handling
```htmlmixed=
<form method="GET">
<input type="text" name="color">
<input type="submit" value="submit">
</form>
```
* `echo $_GET["xxxx"];`
* `echo $_POST["xxxx"];`
* used to specify which file should handle data from the form request
```htmlmixed=
<form method="GET" action="hihi.php">
<input type="text" name="color">
<input type="submit" value="submit">
</form>
```
* `$_SERVER["REQUEST_METHOD"] === "POST"`
## Condition
* `>`, `<`...
* `===`, `!==`
* `&&`, `||`, `and`, `or`, `xor`
```htmlmixed=
if(){
}
elseif(){
}
else{
}
```
* `$link_color = $isClicked ? "purple" : "blue";`
```htmlmixed=
switch ($letter_grade){
case "C":
case "A":
echo "Terrific";
break;
case "B":
echo "Good";
break;
default:
echo "Invalid grade";
}
```
* false
* Empty strings
* `null`
* an undefined or undeclared variable
* an empty array
* the number `0`
* the string `"0"`
* `readline("Hello, ~~~")`
* 輸出 `Hello, ~~~`,並要求輸入
## Loop
* while
```htmlmixed=
while(){
}
```
* do...while
```htmlmixed==
do{
}while();
```
* for
```htmlmixed=
for ($count = 1; $count < 11; $count++){
}
```
* foreach
```htmlmixed=
$counting_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
foreach ($counting_array as $count) {
echo "The count is: " . $count . "\n";
}
$details_array = ["color" => "blue", "shape" => "square"];
foreach ($details_array as $detail) {
echo "The detail is: " . $detail . "\n";
}
//The detail is: blue
//The detail is: square
$details_array = ["color" => "blue", "shape" => "square"];
foreach ($details_array as $attribute => $detail) {
echo "The " . $attribute . " is: " . $detail . "\n";
}
//The color is: blue
//The shape is: square
```
* `break`, `continue`
### Loop with HTML
```htmlmixed=
<ul>
<?php
for ($i = 0; $i < 2; $i++):
?>
<li>Duck</li>
<?php
endfor;
?>
<li>Goose</li>
</ul>
```
* `while():`, `endwhile;`
* `foreach`, `endforeach;`
## Regular Expression
* `[\w]`
* word character, `[A-Za-z0-9_]`
* `[\d]`
* digit character, `[0-9]`
* `[\s]`
* whitespace character, `[ \t\r\n\f\v]`
* `[\W]`
* non-word character
* `[\D]`
* non-digit character
* `[\S]`
* non-whitespace character
* `()`
* `{times}`
* `{from, to}`
* `?`
* 0 or 1 遍
* `*`
* >= 0 遍
* `^`
* `^word`
* start
* `$`
* `word$`
* end
---
###### tags: `Web`