티스토리 뷰

<VARIABLES>

Types

- String/ Integer/ Float/ Boolean/ Array/ Object/ NULL/ Resource(Special var holding a resource)

Rules

- It is prefixed with $.

- It starts with a letter of the underscore character.

- It cannot start with a number

- It contains only alpha-numeric characters and underscores (A-z, 0-9 and _)

- CASE-SENSITIVE

Examples

$name = 'Dariya';
$age = 29;
$has_children = false;

echo $name . ' is ' . $age . ' years old'; 
// '.' functions concatenation and can be replaced with '+'.

echo "${name} is ${age} years old";
// The most recommended way of concatenation.

define ('DB_NAME', 'book_db'); 
// === $DB_NAME = 'book_db);

 

Arrays

    $numbers = [1,3,5,7,9];
    $veggies = ['Eggplant', 'Carrot', 'Avocado'];

 

Associative Array  = It is an array storing key value pairs.

   $colours = [
        1 => 'purple',
        2 => 'yellow',
        5 => 'blue',
    ];

    echo $colours[5]; // => blue

 

Multidemensional Array  = It is an array with more than two dimensions. 

 $students = [
        ['f_name' => 'Kim', 'l_name' => 'Agrafena',],
        ['f_name' => 'Ivanova', 'l_name' => 'Anastasia',],
        ['f_name' => 'Kumova', 'l_name' => 'Alena',],
    ];

    echo $students[1]['f_name']; // Ivanova
    var_dump(json_encode($students));

This type of array is frequently to encode/decode json-type data. 

 

<CONDITIONALS>

Types

1. signs: '<', '>', '<=', '>=', '==' equal to, '===' identical to, '!=', '!=='

2. if / if ~ else if ~ else / if ~ else

  $t = date("H");
  
  if($t >= 12) {
    echo 'Good morning';
  } else if($t < 17) {
    echo 'Dovry Djen';
  } else {
    echo 'Dovry Vecher';
  }
  
  // result => 'Good morning' / 9:49AM

3. ternary operator

  	$texts = ['Sample Text#1'];
	echo !empty($texts) ? $texts[0] : 'Not Exist';

4. null coalescing operator

  $fText = $texts[0] ?? null;
  echo $fText;

5. switch

 $favWriter = 'Dostoevsky';

  switch($favWriter) {
    case 'Chehov': 
        echo 'Your favorite writer is Chehov.';
        break;
    case 'Dostoevsky': 
        echo 'Your favorite writer is Dostoevsky.';
        break;
    case 'Gorky': 
        echo 'Your favorite writer is Gorky.';
        break;
    default:
        echo 'UNMATCHED';
  }

 

<LOOP>

Types

1. for (init value; condition; action) {}

  for($i = 0; $i < 5; $i++) {
    echo $i;
  }

2. while (condition) {}

 $i = 1;
  while($i < 7) {
    echo $i;
    $i++;
  }

 3. do {} while (condition); => It executes the action written inside the brackets once at least.

$i = 4;
    do {
    echo $i;
    $i++;
    }  while($i <= 3);
    
//result => 4

4. foreach ($array as $value) {}

 $ex = ['first', 'second', 'third'];
    foreach($ex as $index => $e) {
        echo $index . ' - ' . $e . '<br>';
    }   
//result: 
//0 - first
//1 - second ...

 

<Functions>

Types

1. General 

 function registerMember($email) {
        echo $email . ' has been registered';
    }
 registerMember('agrafenka@gmail.com');

2. Anonymous

    $subtract = function($n1, $n2) {
        return $n1 - $n2;
    };
	echo $subtract(3, 10);

3. Arrow

$divide = fn($n1, $n2) => $n1 / $n2;
echo $divide(3, 10); // 0.3

 

4. Array-related

$veggies = ['avocado', 'tomato', 'celery'];
    //length
    echo count($veggies); // 3
    //search
    var_dump(in_array('tomato', $veggies)); // 'bool(true)'\    
    //add
    $veggies[] = 'carrot';
    array_push($veggies, 'coriander');
    //replace a first value
    array_unshift($veggies, 'onion'); // [0] => onion
    //remove
    array_pop($veggies); 
    array_shift($veggies);
    unset($veggies[2]);
    //split
    $chunked_arr = array_chunk($veggies, 2);
    //merge
    $arr1 = [1,2,3];
    $arr2 = [5,6,7];
    $arr3 = array_merge($arr1, $arr2);
    $arr4 = [...$arr1, ...$arr2]; //spread operator
    //combine
    $m = ['Asia', 'Africa', 'Europe'];
    $g = ['Far East', 'Southeastern', 'Southwestern'];
    $c = array_combine($m, $g);
    print_r($c); // ([Asia] => FarEast [Africa] => Southeastern, ...)
    //give keys
    $keys = array_keys($c);
    //flip
    $flipped = array_flip($c);
    //range
    $nums = range(1,5); // [0] => 1 [1] => 2, ...
    //array map
    $newNums = array_map(function($num) {
        return "Num ${num}";
    }, $nums); // [0] => Num 1 [1] => Num 2, ...
    //filter map
    $lessThan3 = array_filter($nums, fn($num) => $num <= e );
    //reduce map
    //carry holds the return value of the PREVIOUS iteration and $num holds the value of the CURRENT iteration.
    $sum = array_reduce($nums, fn($carry, $num) => $carry + $num); // int(15)

4-1. count() => returns a length.

4-2. in_array() => searches a result matching conditions.

4-3. $veggies[] = 'xxx'; / array_push(array_name, value to add) => add a value. 

4-4. array_unshift(array_name, value to replace) => replace a first value. 

4-5. array_pop(array_name) => remove a last value, array_shift(array_name) => remove a fist value, unset(array_name[index]) => remove a value of the indcated index.

4-6. array_chunk(array_name, pcs) => split into the specific number of chunks.

4-7. array_merge(arr1, arr2), [...arr]<Spread operator> => merge arrays. 

4-8. array_combine(arr1, arr2) => combine arrays. /array_keys

4-9. array_flip(arr) => exchange all keys with their associated values in an array.

4-10. range(start, end) => create an array containa a range of elements. 

4-11. array_map(func(arr_element) { return vale }, arr} => applies the callback to the elements of the given arrays. 

4-12. array_filter(arr, fn(arr_element) =>  condition) => return values matching the condition. 

4-13. array_reduce(arr, callback(mixed, mixed), mixed) => iteratively reduce the array to a single value using a callback function.  

 

5. String-related

5-1. strlen => length.

5-2. strpos($string, 'x') => the position of the first occurrence of a substring.

5-3. strrpos($string, 'x') => the position of the last occurence of a substring.

5-4. strrev => reverse

5-5. strtolower / strtoupper => convert characters to lower/uppercase.

5-6. ucwords => convert the first character of each word to uppercase.

5-7. str_replace(str1, str2, $string)

5-8. substr($string, pos1, pos2)

5-9. str_starts_with($string, str1), str_ends_with($string, str1)

5-10. htmlspecialchars($string) => show html tags with strings.

 

 

 

 

 

 

 

 

Reference: PHP For Beginner | Crash Course (https://www.youtube.com/watch?v=BUCiSSyIGGU&t=1594s)