From 17cb09f99edcab2df5282b471b1023c05695780b Mon Sep 17 00:00:00 2001 From: ola-9 Date: Fri, 21 Jun 2024 15:04:18 +0300 Subject: [PATCH] clean up new structure --- .../10-hello-world/description.en.yml | 42 ----- .../10-hello-world/description.ru.yml | 63 ------- modules/10-basics/10-hello-world/en/data.yml | 1 + modules/10-basics/10-hello-world/es/data.yml | 1 + modules/10-basics/10-hello-world/ru/data.yml | 1 + modules/10-basics/20-tags/description.en.yml | 24 --- modules/10-basics/20-tags/description.ru.yml | 26 --- modules/10-basics/20-tags/en/data.yml | 1 + modules/10-basics/20-tags/es/data.yml | 1 + modules/10-basics/20-tags/ru/data.yml | 1 + .../10-basics/30-comments/description.en.yml | 60 ------- .../10-basics/30-comments/description.es.yml | 2 +- .../10-basics/30-comments/description.ru.yml | 50 ------ modules/10-basics/30-comments/en/data.yml | 1 + modules/10-basics/30-comments/es/data.yml | 1 + modules/10-basics/30-comments/ru/data.yml | 1 + .../40-instructions/description.en.yml | 53 ------ .../40-instructions/description.ru.yml | 53 ------ modules/10-basics/40-instructions/en/data.yml | 1 + modules/10-basics/40-instructions/es/data.yml | 1 + modules/10-basics/40-instructions/ru/data.yml | 1 + .../10-basics/45-testing/description.en.yml | 49 ------ .../10-basics/45-testing/description.ru.yml | 49 ------ modules/10-basics/45-testing/en/data.yml | 1 + modules/10-basics/45-testing/es/data.yml | 1 + modules/10-basics/45-testing/ru/data.yml | 1 + .../50-syntax-errors/description.en.yml | 33 ---- .../50-syntax-errors/description.ru.yml | 34 ---- .../10-basics/50-syntax-errors/en/data.yml | 1 + .../10-basics/50-syntax-errors/es/data.yml | 1 + .../10-basics/50-syntax-errors/ru/data.yml | 1 + modules/10-basics/description.ru.yml | 1 - .../20-basic/description.en.yml | 68 -------- .../20-basic/description.ru.yml | 50 ------ modules/20-arithmetics/20-basic/en/data.yml | 3 +- modules/20-arithmetics/20-basic/es/data.yml | 1 + modules/20-arithmetics/20-basic/ru/data.yml | 1 + .../25-operator/description.en.yml | 59 ------- .../25-operator/description.ru.yml | 62 ------- .../20-arithmetics/25-operator/en/data.yml | 1 + .../20-arithmetics/25-operator/es/data.yml | 1 + .../20-arithmetics/25-operator/ru/data.yml | 1 + .../27-commutativity/description.en.yml | 24 --- .../27-commutativity/description.ru.yml | 19 --- .../27-commutativity/en/data.yml | 1 + .../27-commutativity/es/data.yml | 1 + .../27-commutativity/ru/data.yml | 1 + .../30-composition/description.en.yml | 41 ----- .../30-composition/description.ru.yml | 32 ---- .../20-arithmetics/30-composition/en/data.yml | 1 + .../20-arithmetics/30-composition/es/data.yml | 1 + .../20-arithmetics/30-composition/ru/data.yml | 1 + .../40-priority/description.en.yml | 52 ------ .../40-priority/description.ru.yml | 39 ----- .../20-arithmetics/40-priority/en/data.yml | 1 + .../20-arithmetics/40-priority/es/data.yml | 1 + .../20-arithmetics/40-priority/ru/data.yml | 1 + .../45-linting/description.en.yml | 47 ------ .../45-linting/description.ru.yml | 53 ------ modules/20-arithmetics/45-linting/en/data.yml | 1 + modules/20-arithmetics/45-linting/es/data.yml | 1 + modules/20-arithmetics/45-linting/ru/data.yml | 1 + .../25-strings/10-quotes/description.en.yml | 112 ------------- .../25-strings/10-quotes/description.ru.yml | 110 ------------ modules/25-strings/10-quotes/en/data.yml | 1 + modules/25-strings/10-quotes/es/data.yml | 1 + modules/25-strings/10-quotes/ru/data.yml | 1 + .../15-escape-characters/description.en.yml | 142 ---------------- .../15-escape-characters/description.ru.yml | 64 ------- .../15-escape-characters/en/data.yml | 1 + .../15-escape-characters/es/data.yml | 1 + .../15-escape-characters/ru/data.yml | 1 + .../description.en.yml | 83 ---------- .../description.ru.yml | 63 ------- .../20-strings-concatenation/en/data.yml | 1 + .../20-strings-concatenation/es/data.yml | 1 + .../20-strings-concatenation/ru/data.yml | 1 + .../25-strings/30-encoding/description.en.yml | 71 -------- .../25-strings/30-encoding/description.ru.yml | 71 -------- modules/25-strings/30-encoding/en/data.yml | 1 + modules/25-strings/30-encoding/es/data.yml | 1 + modules/25-strings/30-encoding/ru/data.yml | 1 + modules/25-strings/description.en.yml | 1 - modules/25-strings/description.ru.yml | 1 - .../description.en.yml | 51 ------ .../description.ru.yml | 62 ------- .../40-primitive-data-types/en/data.yml | 1 + .../40-primitive-data-types/es/data.yml | 1 + .../40-primitive-data-types/ru/data.yml | 1 + .../description.en.yml | 33 ---- .../description.ru.yml | 26 --- .../50-data-types-weak-typing/en/data.yml | 1 + .../50-data-types-weak-typing/es/data.yml | 1 + .../50-data-types-weak-typing/ru/data.yml | 1 + .../55-type-conversion/description.en.yml | 53 ------ .../55-type-conversion/description.ru.yml | 38 ----- .../55-type-conversion/en/data.yml | 1 + .../55-type-conversion/es/data.yml | 1 + .../55-type-conversion/ru/data.yml | 1 + modules/27-data-types/description.en.yml | 1 - modules/27-data-types/description.ru.yml | 1 - .../10-definition/description.en.yml | 62 ------- .../10-definition/description.ru.yml | 47 ------ .../30-variables/10-definition/en/data.yml | 1 + .../30-variables/10-definition/es/data.yml | 1 + .../30-variables/10-definition/ru/data.yml | 1 + .../30-variables/12-change/description.en.yml | 37 ----- .../30-variables/12-change/description.ru.yml | 33 ---- modules/30-variables/12-change/en/data.yml | 1 + modules/30-variables/12-change/es/data.yml | 1 + modules/30-variables/12-change/ru/data.yml | 1 + .../13-variables-naming/description.en.yml | 36 ---- .../13-variables-naming/description.ru.yml | 32 ---- .../13-variables-naming/en/data.yml | 1 + .../13-variables-naming/es/data.yml | 1 + .../13-variables-naming/ru/data.yml | 1 + .../30-variables/14-errors/description.en.yml | 31 ---- .../30-variables/14-errors/description.ru.yml | 30 ---- modules/30-variables/14-errors/en/data.yml | 1 + modules/30-variables/14-errors/es/data.yml | 1 + modules/30-variables/14-errors/ru/data.yml | 1 + .../15-expressions/description.en.yml | 97 ----------- .../15-expressions/description.ru.yml | 91 ---------- .../30-variables/15-expressions/en/data.yml | 1 + .../30-variables/15-expressions/es/data.yml | 1 + .../30-variables/15-expressions/ru/data.yml | 1 + .../18-concatenation/description.en.yml | 62 ------- .../18-concatenation/description.ru.yml | 62 ------- .../30-variables/18-concatenation/en/data.yml | 1 + .../30-variables/18-concatenation/es/data.yml | 1 + .../30-variables/18-concatenation/ru/data.yml | 1 + .../19-naming-style/description.en.yml | 33 ---- .../19-naming-style/description.ru.yml | 33 ---- .../30-variables/19-naming-style/en/data.yml | 1 + .../30-variables/19-naming-style/es/data.yml | 1 + .../30-variables/19-naming-style/ru/data.yml | 1 + .../20-magic-numbers/description.en.yml | 70 -------- .../20-magic-numbers/description.ru.yml | 70 -------- .../30-variables/20-magic-numbers/en/data.yml | 1 + .../30-variables/20-magic-numbers/es/data.yml | 1 + .../30-variables/20-magic-numbers/ru/data.yml | 1 + .../23-constants/description.en.yml | 35 ---- .../23-constants/description.ru.yml | 47 ------ modules/30-variables/23-constants/en/data.yml | 1 + modules/30-variables/23-constants/es/data.yml | 1 + modules/30-variables/23-constants/ru/data.yml | 1 + .../24-magic-constants/description.en.yml | 28 ---- .../24-magic-constants/description.ru.yml | 28 ---- .../24-magic-constants/en/data.yml | 1 + .../24-magic-constants/es/data.yml | 1 + .../24-magic-constants/ru/data.yml | 1 + .../25-interpolation/description.en.yml | 50 ------ .../25-interpolation/description.ru.yml | 50 ------ .../30-variables/25-interpolation/en/data.yml | 1 + .../30-variables/25-interpolation/es/data.yml | 1 + .../30-variables/25-interpolation/ru/data.yml | 1 + .../30-symbols/description.en.yml | 64 ------- .../30-symbols/description.ru.yml | 66 -------- modules/30-variables/30-symbols/en/data.yml | 1 + modules/30-variables/30-symbols/es/data.yml | 1 + modules/30-variables/30-symbols/ru/data.yml | 1 + .../35-heredoc/description.en.yml | 40 ----- .../35-heredoc/description.ru.yml | 36 ---- modules/30-variables/35-heredoc/en/data.yml | 1 + modules/30-variables/35-heredoc/es/data.yml | 1 + modules/30-variables/35-heredoc/ru/data.yml | 1 + .../100-call/description.en.yml | 80 --------- .../100-call/description.ru.yml | 79 --------- .../35-calling-functions/100-call/en/data.yml | 1 + .../35-calling-functions/100-call/es/data.yml | 1 + .../35-calling-functions/100-call/ru/data.yml | 1 + .../120-function-signature/description.en.yml | 46 ------ .../120-function-signature/description.ru.yml | 87 ---------- .../120-function-signature/en/data.yml | 1 + .../120-function-signature/es/data.yml | 1 + .../120-function-signature/ru/data.yml | 1 + .../description.en.yml | 42 ----- .../description.ru.yml | 42 ----- .../en/data.yml | 1 + .../es/data.yml | 1 + .../ru/data.yml | 1 + .../description.en.yml | 79 --------- .../description.ru.yml | 74 --------- .../en/data.yml | 1 + .../es/data.yml | 1 + .../ru/data.yml | 1 + .../180-variadic-arguments/description.en.yml | 36 ---- .../180-variadic-arguments/description.ru.yml | 29 ---- .../180-variadic-arguments/en/data.yml | 1 + .../180-variadic-arguments/es/data.yml | 1 + .../180-variadic-arguments/ru/data.yml | 1 + .../270-deterministic/description.en.yml | 32 ---- .../270-deterministic/description.ru.yml | 69 -------- .../270-deterministic/en/data.yml | 1 + .../270-deterministic/es/data.yml | 1 + .../270-deterministic/ru/data.yml | 1 + .../900-stdlib/description.en.yml | 30 ---- .../900-stdlib/description.es.yml | 10 +- .../900-stdlib/description.ru.yml | 33 ---- .../900-stdlib/en/data.yml | 1 + .../900-stdlib/es/data.yml | 1 + .../900-stdlib/ru/data.yml | 1 + .../100-define/description.en.yml | 78 --------- .../100-define/description.ru.yml | 87 ---------- .../100-define/en/data.yml | 1 + .../100-define/es/data.yml | 1 + .../100-define/ru/data.yml | 1 + .../200-return/description.en.yml | 150 ----------------- .../200-return/description.ru.yml | 156 ------------------ .../200-return/en/data.yml | 1 + .../200-return/es/data.yml | 1 + .../200-return/ru/data.yml | 1 + .../300-parameters/description.en.yml | 108 ------------ .../300-parameters/description.ru.yml | 108 ------------ .../300-parameters/en/data.yml | 1 + .../300-parameters/es/data.yml | 1 + .../300-parameters/ru/data.yml | 1 + .../340-default-parameters/description.en.yml | 99 ----------- .../340-default-parameters/description.ru.yml | 100 ----------- .../340-default-parameters/en/data.yml | 1 + .../340-default-parameters/es/data.yml | 1 + .../340-default-parameters/ru/data.yml | 1 + .../description.en.yml | 49 ------ .../description.ru.yml | 54 ------ .../500-reading-documentation/en/data.yml | 1 + .../500-reading-documentation/es/data.yml | 1 + .../500-reading-documentation/ru/data.yml | 1 + .../45-logic/10-bool-type/description.en.yml | 93 ----------- .../45-logic/10-bool-type/description.ru.yml | 71 -------- modules/45-logic/10-bool-type/en/data.yml | 1 + modules/45-logic/10-bool-type/es/data.yml | 1 + modules/45-logic/10-bool-type/ru/data.yml | 1 + .../45-logic/15-predicates/description.en.yml | 67 -------- .../45-logic/15-predicates/description.ru.yml | 45 ----- modules/45-logic/15-predicates/en/data.yml | 1 + modules/45-logic/15-predicates/es/data.yml | 1 + modules/45-logic/15-predicates/ru/data.yml | 1 + .../description.en.yml | 113 ------------- .../description.ru.yml | 67 -------- .../20-logic-combine-expressions/en/data.yml | 1 + .../20-logic-combine-expressions/es/data.yml | 1 + .../20-logic-combine-expressions/ru/data.yml | 1 + .../25-logical-operators/description.en.yml | 147 ----------------- .../25-logical-operators/description.ru.yml | 92 ----------- .../45-logic/25-logical-operators/en/data.yml | 1 + .../45-logic/25-logical-operators/es/data.yml | 1 + .../45-logic/25-logical-operators/ru/data.yml | 1 + .../28-logical-negation/description.en.yml | 68 -------- .../28-logical-negation/description.es.yml | 2 +- .../28-logical-negation/description.ru.yml | 59 ------- .../45-logic/28-logical-negation/en/data.yml | 1 + .../45-logic/28-logical-negation/es/data.yml | 1 + .../45-logic/28-logical-negation/ru/data.yml | 1 + .../29-logical-operators-2/description.en.yml | 49 ------ .../29-logical-operators-2/description.ru.yml | 49 ------ .../29-logical-operators-2/en/data.yml | 1 + .../29-logical-operators-2/es/data.yml | 1 + .../29-logical-operators-2/ru/data.yml | 1 + .../70-logic-weak-typing/description.en.yml | 113 ------------- .../70-logic-weak-typing/description.ru.yml | 75 --------- .../45-logic/70-logic-weak-typing/en/data.yml | 1 + .../45-logic/70-logic-weak-typing/es/data.yml | 1 + .../45-logic/70-logic-weak-typing/ru/data.yml | 1 + .../48-conditionals/30-if/description.en.yml | 70 -------- .../48-conditionals/30-if/description.ru.yml | 46 ------ modules/48-conditionals/30-if/en/data.yml | 1 + modules/48-conditionals/30-if/es/data.yml | 1 + modules/48-conditionals/30-if/ru/data.yml | 1 + .../40-if-else/description.en.yml | 76 --------- .../40-if-else/description.ru.yml | 75 --------- .../48-conditionals/40-if-else/en/data.yml | 1 + .../48-conditionals/40-if-else/es/data.yml | 1 + .../48-conditionals/40-if-else/ru/data.yml | 1 + .../50-else-if/description.en.yml | 95 ----------- .../50-else-if/description.ru.yml | 95 ----------- .../48-conditionals/50-else-if/en/data.yml | 1 + .../48-conditionals/50-else-if/es/data.yml | 1 + .../48-conditionals/50-else-if/ru/data.yml | 1 + .../60-ternary-operator/description.en.yml | 100 ----------- .../60-ternary-operator/description.ru.yml | 101 ------------ .../60-ternary-operator/en/data.yml | 1 + .../60-ternary-operator/es/data.yml | 1 + .../60-ternary-operator/ru/data.yml | 1 + .../65-switch/description.en.yml | 130 --------------- .../65-switch/description.ru.yml | 134 --------------- modules/48-conditionals/65-switch/en/data.yml | 1 + modules/48-conditionals/65-switch/es/data.yml | 1 + modules/48-conditionals/65-switch/ru/data.yml | 1 + .../75-elvis/description.en.yml | 82 --------- .../75-elvis/description.ru.yml | 79 --------- modules/48-conditionals/75-elvis/en/data.yml | 1 + modules/48-conditionals/75-elvis/es/data.yml | 1 + modules/48-conditionals/75-elvis/ru/data.yml | 1 + modules/50-loops/10-while/description.en.yml | 150 ----------------- modules/50-loops/10-while/description.ru.yml | 153 ----------------- modules/50-loops/10-while/en/data.yml | 1 + modules/50-loops/10-while/es/data.yml | 1 + modules/50-loops/10-while/ru/data.yml | 1 + .../20-aggregation-numbers/description.en.yml | 100 ----------- .../20-aggregation-numbers/description.ru.yml | 113 ------------- .../20-aggregation-numbers/en/data.yml | 1 + .../20-aggregation-numbers/es/data.yml | 1 + .../20-aggregation-numbers/ru/data.yml | 1 + .../23-aggregation-strings/description.en.yml | 61 ------- .../23-aggregation-strings/description.ru.yml | 60 ------- .../23-aggregation-strings/en/data.yml | 1 + .../23-aggregation-strings/es/data.yml | 1 + .../23-aggregation-strings/ru/data.yml | 1 + .../description.en.yml | 53 ------ .../description.ru.yml | 58 ------- .../25-iteration-over-string/en/data.yml | 1 + .../25-iteration-over-string/es/data.yml | 1 + .../25-iteration-over-string/ru/data.yml | 1 + .../description.en.yml | 60 ------- .../description.ru.yml | 60 ------- .../26-conditions-inside-loops/en/data.yml | 1 + .../26-conditions-inside-loops/es/data.yml | 1 + .../26-conditions-inside-loops/ru/data.yml | 1 + .../28-build-strings/description.en.yml | 67 -------- .../28-build-strings/description.ru.yml | 67 -------- modules/50-loops/28-build-strings/en/data.yml | 1 + modules/50-loops/28-build-strings/es/data.yml | 1 + modules/50-loops/28-build-strings/ru/data.yml | 1 + .../50-loops/29-edge-cases/description.en.yml | 74 --------- .../50-loops/29-edge-cases/description.ru.yml | 111 ------------- modules/50-loops/29-edge-cases/en/data.yml | 1 + modules/50-loops/29-edge-cases/es/data.yml | 1 + modules/50-loops/29-edge-cases/ru/data.yml | 1 + .../30-syntax-sugar/description.en.yml | 29 ---- .../30-syntax-sugar/description.ru.yml | 29 ---- modules/50-loops/30-syntax-sugar/en/data.yml | 1 + modules/50-loops/30-syntax-sugar/es/data.yml | 1 + modules/50-loops/30-syntax-sugar/ru/data.yml | 1 + .../50-loops/50-mutators/description.en.yml | 86 ---------- .../50-loops/50-mutators/description.ru.yml | 85 ---------- modules/50-loops/50-mutators/en/data.yml | 1 + modules/50-loops/50-mutators/es/data.yml | 1 + modules/50-loops/50-mutators/ru/data.yml | 1 + .../55-return-from-loop/description.en.yml | 66 -------- .../55-return-from-loop/description.ru.yml | 66 -------- .../50-loops/55-return-from-loop/en/data.yml | 1 + .../50-loops/55-return-from-loop/es/data.yml | 1 + .../50-loops/55-return-from-loop/ru/data.yml | 1 + modules/50-loops/70-for/description.en.yml | 58 ------- modules/50-loops/70-for/description.ru.yml | 61 ------- modules/50-loops/70-for/en/data.yml | 1 + modules/50-loops/70-for/es/data.yml | 1 + modules/50-loops/70-for/ru/data.yml | 1 + .../10-unicode/description.en.yml | 59 ------- .../10-unicode/description.ru.yml | 92 ----------- .../10-unicode/en/data.yml | 1 + .../10-unicode/es/data.yml | 1 + .../10-unicode/ru/data.yml | 1 + .../30-locales/description.en.yml | 45 ----- .../30-locales/description.ru.yml | 47 ------ .../30-locales/en/data.yml | 1 + .../30-locales/es/data.yml | 1 + .../30-locales/ru/data.yml | 1 + .../40-startwith/description.en.yml | 51 ------ .../40-startwith/description.ru.yml | 51 ------ .../40-startwith/en/data.yml | 1 + .../40-startwith/es/data.yml | 1 + .../40-startwith/ru/data.yml | 1 + .../70-dates/10-timestamp/description.en.yml | 37 ----- .../70-dates/10-timestamp/description.ru.yml | 43 ----- modules/70-dates/10-timestamp/en/data.yml | 1 + modules/70-dates/10-timestamp/es/data.yml | 1 + modules/70-dates/10-timestamp/ru/data.yml | 1 + modules/70-dates/20-date/description.en.yml | 49 ------ modules/70-dates/20-date/description.ru.yml | 49 ------ modules/70-dates/20-date/en/data.yml | 1 + modules/70-dates/20-date/es/data.yml | 1 + modules/70-dates/20-date/ru/data.yml | 1 + modules/70-dates/30-mktime/description.en.yml | 32 ---- modules/70-dates/30-mktime/description.ru.yml | 38 ----- modules/70-dates/30-mktime/en/data.yml | 1 + modules/70-dates/30-mktime/es/data.yml | 1 + modules/70-dates/30-mktime/ru/data.yml | 1 + .../70-dates/40-timezone/description.en.yml | 22 --- .../70-dates/40-timezone/description.ru.yml | 23 --- modules/70-dates/40-timezone/en/data.yml | 1 + modules/70-dates/40-timezone/es/data.yml | 1 + modules/70-dates/40-timezone/ru/data.yml | 1 + 383 files changed, 233 insertions(+), 9587 deletions(-) delete mode 100644 modules/10-basics/10-hello-world/description.en.yml delete mode 100644 modules/10-basics/10-hello-world/description.ru.yml delete mode 100644 modules/10-basics/20-tags/description.en.yml delete mode 100644 modules/10-basics/20-tags/description.ru.yml delete mode 100644 modules/10-basics/30-comments/description.en.yml delete mode 100644 modules/10-basics/30-comments/description.ru.yml delete mode 100644 modules/10-basics/40-instructions/description.en.yml delete mode 100644 modules/10-basics/40-instructions/description.ru.yml delete mode 100644 modules/10-basics/45-testing/description.en.yml delete mode 100644 modules/10-basics/45-testing/description.ru.yml delete mode 100644 modules/10-basics/50-syntax-errors/description.en.yml delete mode 100644 modules/10-basics/50-syntax-errors/description.ru.yml delete mode 100644 modules/20-arithmetics/20-basic/description.en.yml delete mode 100644 modules/20-arithmetics/20-basic/description.ru.yml delete mode 100644 modules/20-arithmetics/25-operator/description.en.yml delete mode 100644 modules/20-arithmetics/25-operator/description.ru.yml delete mode 100644 modules/20-arithmetics/27-commutativity/description.en.yml delete mode 100644 modules/20-arithmetics/27-commutativity/description.ru.yml delete mode 100644 modules/20-arithmetics/30-composition/description.en.yml delete mode 100644 modules/20-arithmetics/30-composition/description.ru.yml delete mode 100644 modules/20-arithmetics/40-priority/description.en.yml delete mode 100644 modules/20-arithmetics/40-priority/description.ru.yml delete mode 100644 modules/20-arithmetics/45-linting/description.en.yml delete mode 100644 modules/20-arithmetics/45-linting/description.ru.yml delete mode 100644 modules/25-strings/10-quotes/description.en.yml delete mode 100644 modules/25-strings/10-quotes/description.ru.yml delete mode 100644 modules/25-strings/15-escape-characters/description.en.yml delete mode 100644 modules/25-strings/15-escape-characters/description.ru.yml delete mode 100644 modules/25-strings/20-strings-concatenation/description.en.yml delete mode 100644 modules/25-strings/20-strings-concatenation/description.ru.yml delete mode 100644 modules/25-strings/30-encoding/description.en.yml delete mode 100644 modules/25-strings/30-encoding/description.ru.yml delete mode 100644 modules/27-data-types/40-primitive-data-types/description.en.yml delete mode 100644 modules/27-data-types/40-primitive-data-types/description.ru.yml delete mode 100644 modules/27-data-types/50-data-types-weak-typing/description.en.yml delete mode 100644 modules/27-data-types/50-data-types-weak-typing/description.ru.yml delete mode 100644 modules/27-data-types/55-type-conversion/description.en.yml delete mode 100644 modules/27-data-types/55-type-conversion/description.ru.yml delete mode 100644 modules/30-variables/10-definition/description.en.yml delete mode 100644 modules/30-variables/10-definition/description.ru.yml delete mode 100644 modules/30-variables/12-change/description.en.yml delete mode 100644 modules/30-variables/12-change/description.ru.yml delete mode 100644 modules/30-variables/13-variables-naming/description.en.yml delete mode 100644 modules/30-variables/13-variables-naming/description.ru.yml delete mode 100644 modules/30-variables/14-errors/description.en.yml delete mode 100644 modules/30-variables/14-errors/description.ru.yml delete mode 100644 modules/30-variables/15-expressions/description.en.yml delete mode 100644 modules/30-variables/15-expressions/description.ru.yml delete mode 100644 modules/30-variables/18-concatenation/description.en.yml delete mode 100644 modules/30-variables/18-concatenation/description.ru.yml delete mode 100644 modules/30-variables/19-naming-style/description.en.yml delete mode 100644 modules/30-variables/19-naming-style/description.ru.yml delete mode 100644 modules/30-variables/20-magic-numbers/description.en.yml delete mode 100644 modules/30-variables/20-magic-numbers/description.ru.yml delete mode 100644 modules/30-variables/23-constants/description.en.yml delete mode 100644 modules/30-variables/23-constants/description.ru.yml delete mode 100644 modules/30-variables/24-magic-constants/description.en.yml delete mode 100644 modules/30-variables/24-magic-constants/description.ru.yml delete mode 100644 modules/30-variables/25-interpolation/description.en.yml delete mode 100644 modules/30-variables/25-interpolation/description.ru.yml delete mode 100644 modules/30-variables/30-symbols/description.en.yml delete mode 100644 modules/30-variables/30-symbols/description.ru.yml delete mode 100644 modules/30-variables/35-heredoc/description.en.yml delete mode 100644 modules/30-variables/35-heredoc/description.ru.yml delete mode 100644 modules/35-calling-functions/100-call/description.en.yml delete mode 100644 modules/35-calling-functions/100-call/description.ru.yml delete mode 100644 modules/35-calling-functions/120-function-signature/description.en.yml delete mode 100644 modules/35-calling-functions/120-function-signature/description.ru.yml delete mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/description.en.yml delete mode 100644 modules/35-calling-functions/135-calling-functions-default-arguments/description.ru.yml delete mode 100644 modules/35-calling-functions/150-calling-functions-expression/description.en.yml delete mode 100644 modules/35-calling-functions/150-calling-functions-expression/description.ru.yml delete mode 100644 modules/35-calling-functions/180-variadic-arguments/description.en.yml delete mode 100644 modules/35-calling-functions/180-variadic-arguments/description.ru.yml delete mode 100644 modules/35-calling-functions/270-deterministic/description.en.yml delete mode 100644 modules/35-calling-functions/270-deterministic/description.ru.yml delete mode 100644 modules/35-calling-functions/900-stdlib/description.en.yml delete mode 100644 modules/35-calling-functions/900-stdlib/description.ru.yml delete mode 100644 modules/40-define-functions/100-define/description.en.yml delete mode 100644 modules/40-define-functions/100-define/description.ru.yml delete mode 100644 modules/40-define-functions/200-return/description.en.yml delete mode 100644 modules/40-define-functions/200-return/description.ru.yml delete mode 100644 modules/40-define-functions/300-parameters/description.en.yml delete mode 100644 modules/40-define-functions/300-parameters/description.ru.yml delete mode 100644 modules/40-define-functions/340-default-parameters/description.en.yml delete mode 100644 modules/40-define-functions/340-default-parameters/description.ru.yml delete mode 100644 modules/40-define-functions/500-reading-documentation/description.en.yml delete mode 100644 modules/40-define-functions/500-reading-documentation/description.ru.yml delete mode 100644 modules/45-logic/10-bool-type/description.en.yml delete mode 100644 modules/45-logic/10-bool-type/description.ru.yml delete mode 100644 modules/45-logic/15-predicates/description.en.yml delete mode 100644 modules/45-logic/15-predicates/description.ru.yml delete mode 100644 modules/45-logic/20-logic-combine-expressions/description.en.yml delete mode 100644 modules/45-logic/20-logic-combine-expressions/description.ru.yml delete mode 100644 modules/45-logic/25-logical-operators/description.en.yml delete mode 100644 modules/45-logic/25-logical-operators/description.ru.yml delete mode 100644 modules/45-logic/28-logical-negation/description.en.yml delete mode 100644 modules/45-logic/28-logical-negation/description.ru.yml delete mode 100644 modules/45-logic/29-logical-operators-2/description.en.yml delete mode 100644 modules/45-logic/29-logical-operators-2/description.ru.yml delete mode 100644 modules/45-logic/70-logic-weak-typing/description.en.yml delete mode 100644 modules/45-logic/70-logic-weak-typing/description.ru.yml delete mode 100644 modules/48-conditionals/30-if/description.en.yml delete mode 100644 modules/48-conditionals/30-if/description.ru.yml delete mode 100644 modules/48-conditionals/40-if-else/description.en.yml delete mode 100644 modules/48-conditionals/40-if-else/description.ru.yml delete mode 100644 modules/48-conditionals/50-else-if/description.en.yml delete mode 100644 modules/48-conditionals/50-else-if/description.ru.yml delete mode 100644 modules/48-conditionals/60-ternary-operator/description.en.yml delete mode 100644 modules/48-conditionals/60-ternary-operator/description.ru.yml delete mode 100644 modules/48-conditionals/65-switch/description.en.yml delete mode 100644 modules/48-conditionals/65-switch/description.ru.yml delete mode 100644 modules/48-conditionals/75-elvis/description.en.yml delete mode 100644 modules/48-conditionals/75-elvis/description.ru.yml delete mode 100644 modules/50-loops/10-while/description.en.yml delete mode 100644 modules/50-loops/10-while/description.ru.yml delete mode 100644 modules/50-loops/20-aggregation-numbers/description.en.yml delete mode 100644 modules/50-loops/20-aggregation-numbers/description.ru.yml delete mode 100644 modules/50-loops/23-aggregation-strings/description.en.yml delete mode 100644 modules/50-loops/23-aggregation-strings/description.ru.yml delete mode 100644 modules/50-loops/25-iteration-over-string/description.en.yml delete mode 100644 modules/50-loops/25-iteration-over-string/description.ru.yml delete mode 100644 modules/50-loops/26-conditions-inside-loops/description.en.yml delete mode 100644 modules/50-loops/26-conditions-inside-loops/description.ru.yml delete mode 100644 modules/50-loops/28-build-strings/description.en.yml delete mode 100644 modules/50-loops/28-build-strings/description.ru.yml delete mode 100644 modules/50-loops/29-edge-cases/description.en.yml delete mode 100644 modules/50-loops/29-edge-cases/description.ru.yml delete mode 100644 modules/50-loops/30-syntax-sugar/description.en.yml delete mode 100644 modules/50-loops/30-syntax-sugar/description.ru.yml delete mode 100644 modules/50-loops/50-mutators/description.en.yml delete mode 100644 modules/50-loops/50-mutators/description.ru.yml delete mode 100644 modules/50-loops/55-return-from-loop/description.en.yml delete mode 100644 modules/50-loops/55-return-from-loop/description.ru.yml delete mode 100644 modules/50-loops/70-for/description.en.yml delete mode 100644 modules/50-loops/70-for/description.ru.yml delete mode 100644 modules/60-deep-into-strings/10-unicode/description.en.yml delete mode 100644 modules/60-deep-into-strings/10-unicode/description.ru.yml delete mode 100644 modules/60-deep-into-strings/30-locales/description.en.yml delete mode 100644 modules/60-deep-into-strings/30-locales/description.ru.yml delete mode 100644 modules/60-deep-into-strings/40-startwith/description.en.yml delete mode 100644 modules/60-deep-into-strings/40-startwith/description.ru.yml delete mode 100644 modules/70-dates/10-timestamp/description.en.yml delete mode 100644 modules/70-dates/10-timestamp/description.ru.yml delete mode 100644 modules/70-dates/20-date/description.en.yml delete mode 100644 modules/70-dates/20-date/description.ru.yml delete mode 100644 modules/70-dates/30-mktime/description.en.yml delete mode 100644 modules/70-dates/30-mktime/description.ru.yml delete mode 100644 modules/70-dates/40-timezone/description.en.yml delete mode 100644 modules/70-dates/40-timezone/description.ru.yml diff --git a/modules/10-basics/10-hello-world/description.en.yml b/modules/10-basics/10-hello-world/description.en.yml deleted file mode 100644 index 9633368d..00000000 --- a/modules/10-basics/10-hello-world/description.en.yml +++ /dev/null @@ -1,42 +0,0 @@ ---- - -name: Hello, World! -theory: | - As is our tradition, we'll begin by writing the 'Hello, World!' program. The program will print the following text: - -
-  Hello, World!
-  
- - Output to the screen is done with a special command `echo`, followed by a single or double-quoted string to be output. Be sure to put a semicolon at the end. - - ```php - Hello, World! - ``` - - https://replit.com/@hexlet/php-basics-hello-world-echo - - There are other ways to display a string on the screen. For example, you can use the function (a concept we will get to know later) `print_r()`. In this case, the string is entered in parentheses immediately after the function name. You also need to put `;` at the end. - - ```php - Hello, World! - ``` - - https://replit.com/@hexlet/php-basics-hello-world-echo - - Вывод на экран выполняется с помощью специальной команды `echo`. После нее в одиночных кавычках указывается строка для вывода. В конце обязательно ставим точку с запятой. - - Для удобства мы будем показывать результат запуска строк кода так: `=> РЕЗУЛЬТАТ`. - - ### Пишем программу через `print_r()` - - Другой способ вывести строку на экран — функция `print_r()`: - - ```php - Hello, World! - ``` - - https://replit.com/@hexlet/php-basics-hello-world-printr - - В этом случае строка указывается в скобках сразу после имени функции. В конце также нужно ставить `;`. - - В простых ситуациях между этими конструкциями нет разницы. Можно использовать любой способ. А там, где на экран нужно выводить не просто числа или строки, а, например, массивы, `echo` не сможет этого сделать, а `print_r()` все выведет. - -instructions: | - Наберите в редакторе код из задания символ в символ и нажмите «Проверить». - - ```php - diff --git a/modules/10-basics/10-hello-world/ru/data.yml b/modules/10-basics/10-hello-world/ru/data.yml index 1a060c77..d4c4aba6 100644 --- a/modules/10-basics/10-hello-world/ru/data.yml +++ b/modules/10-basics/10-hello-world/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Привет, Мир! tips: - > diff --git a/modules/10-basics/20-tags/description.en.yml b/modules/10-basics/20-tags/description.en.yml deleted file mode 100644 index bcadfcc5..00000000 --- a/modules/10-basics/20-tags/description.en.yml +++ /dev/null @@ -1,24 +0,0 @@ ---- - -name: Tags -theory: | - PHP is probably the only language in which you can't start writing code right away. Such code will be perceived by the interpreter (the program executing the code) as plain text. Any PHP code should be wrapped in a `` construct. - - `` is the closing tag. PHP allows you to omit the closing part `?>`. And the PSR-12 code manual doesn't let you include it at all. - -instructions: | - Type the code from the example, and put the ``. Это особенность данного языка программирования. - - `` — закрывающий тег. PHP позволяет не указывать закрывающую часть `?>`. А руководство по оформлению кода PSR-12 запрещает ее указывать. - -instructions: | - Наберите код из примера, поставьте в начале тег `- diff --git a/modules/10-basics/30-comments/description.en.yml b/modules/10-basics/30-comments/description.en.yml deleted file mode 100644 index c634c770..00000000 --- a/modules/10-basics/30-comments/description.en.yml +++ /dev/null @@ -1,60 +0,0 @@ ---- - -name: Comments -theory: | - - Almost every programming language allows you to add comments to your code. This is text that isn't part of the program and is needed for programmers to make notes. They help explain how the code works, what errors need to be corrected, or what not to forget to add later. - - Comments in PHP come in two flavors: - - ## Single line comments - - _Single line comments start with `//`. Any text can go after these characters, the whole line will be left alone when the program is run. - - A comment can take up a whole line. Or you can create several comments if one line isn't enough: - - ```php - - Mother of Dragons. Dracarys! - - - Theoretically, the instructions can be written one after the other without moving them to a new line: - - ```php - - RobertStannisRenly - - - Use a `print_r()` call for each name. - -tips: - - | - [A little about interpreters](https://en.wikipedia.org/wiki/Interpreter_(computing)) - -definitions: - - name: The interpreter - description: | - is a program that runs the code in PHP. - - name: An instruction (statement) - description: | - is a command for a computer written in a programming language. PHP code is a set of instructions separated (most often) by a `;`. diff --git a/modules/10-basics/40-instructions/description.ru.yml b/modules/10-basics/40-instructions/description.ru.yml deleted file mode 100644 index 25beca72..00000000 --- a/modules/10-basics/40-instructions/description.ru.yml +++ /dev/null @@ -1,53 +0,0 @@ ---- - -name: Инструкции (Statements) -theory: | - ## Что такое инструкция - - **Инструкция** — это команда, которую исполняет интерпретатор PHP. Она написана на языке программирования. Ее можно сравнить с инструкцией или рецептом по приготовлению блюда: - - Код на PHP — это набор инструкций, которые отделяются друг от друга символом `;`. - - Вот пример кода с двумя инструкциями: - - ```php - Mother of Dragons. Dracarys! - ``` - - При запуске этого кода на экран последовательно выводятся два предложения: `Mother of Dragons. Dracarys!`. - - Инструкции можно написать последовательно друг за другом без переноса на новую строчку: - - ```php - Mother of Dragons. Dracarys! - ``` - - Результат на экране будет таким же. Но такой код неудобно читать, поэтому инструкции располагают друг под другом. - -instructions: | - Выведите на экран друг за другом три имени: _Robert_, _Stannis_, _Renly_. В результате на экране должно отобразиться: - -
-  RobertStannisRenly
-  
- - Для каждого имени используйте свой собственный вызов `print_r()`. - -tips: - - | - [Немного об интерпретаторах](https://ru.wikipedia.org/wiki/Интерпретатор) - -definitions: - - name: Интерпретатор - description: | - программа, выполняющая код на PHP. - - name: Инструкция (statement) - description: | - команда для компьютера, написанная на языке программирования. Код на PHP — это набор инструкций, разделенных (чаще всего) символом `;`. diff --git a/modules/10-basics/40-instructions/en/data.yml b/modules/10-basics/40-instructions/en/data.yml index f1b9a442..f86cc96b 100644 --- a/modules/10-basics/40-instructions/en/data.yml +++ b/modules/10-basics/40-instructions/en/data.yml @@ -1,3 +1,4 @@ +--- name: Statements tips: - > diff --git a/modules/10-basics/40-instructions/es/data.yml b/modules/10-basics/40-instructions/es/data.yml index b10187ee..e18f7404 100644 --- a/modules/10-basics/40-instructions/es/data.yml +++ b/modules/10-basics/40-instructions/es/data.yml @@ -1,3 +1,4 @@ +--- name: Instrucciones tips: - > diff --git a/modules/10-basics/40-instructions/ru/data.yml b/modules/10-basics/40-instructions/ru/data.yml index d2aad354..0021810c 100644 --- a/modules/10-basics/40-instructions/ru/data.yml +++ b/modules/10-basics/40-instructions/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Инструкции (Statements) tips: - | diff --git a/modules/10-basics/45-testing/description.en.yml b/modules/10-basics/45-testing/description.en.yml deleted file mode 100644 index 67ce940c..00000000 --- a/modules/10-basics/45-testing/description.en.yml +++ /dev/null @@ -1,49 +0,0 @@ ---- - -name: How we test your solutions -theory: | - - Our site automatically checks your solutions. You may be wondering how it works. - - In the simplest case, the system just runs the code and looks at what's displayed on the screen. Then it compares the actual output against the expected one. - - In the future, more complicated lessons, you will write functions - mini-programs that take information from the external world and perform operations on it. Verifying solutions gets a little more complicated in this case. The system runs your code and passes data to it. The system knows what result a correctly written function would give with the data the system provides it with, and this result is what the system expects. - - Let's assume your task is to program a function that adds two numbers together. The checking system will give it several combinations of numbers and compare your function's answers with the correct answers. If all actual values match the expected ones, your solution will be considered valid. - - This is testing. It's used extensively in the real, day-to-day development process. Developers usually write the tests first, and only after that do they actually proceed to write the program itself. During that process, they run tests multiple times to check how close they are to the desired solution. - - That is why our website says, “Tests passed” once you've done the exercise correctly. - - Here's a simple example, say you want to print the string `Hello, World!`. Now imagine you make a small mistake and the function displays a different value. In that case, the system will give you the following message: - -
-    -'Hello, World!'
-    +'ello, World!'
-
-    FAILURES!
-    Tests: 1, Assertions: 1, Failures: 1.
-  
- - A hint appears on the screen. The `+` sign on it indicates what your code printed. The `-` sign is what was expected. By comparing the two values, you can see the error. In the example above, you can see that the letter _H_ is missing from the output. - - In addition to our tests, it'll also be extremely useful to experiment with code. To do this, you can use [repl.it](https://repl.it/languages/php). Ideally, you should execute all the code in the lessons yourself. - - --- - - Sometimes, it'll seem that you've done everything correctly, but the system seems to be fickle and won't make a decision. It's nigh on impossible for the system to just decide that it's wrong. Failed tests simply won't get as far as the site, they're automatically run after each change. In the vast majority of cases (all our projects have been run millions of times in total over many years) the error is in the solution code. It can be very imperceptible, maybe you used the wrong punctuation, or you used upper case instead of lower case, or you missed a comma. Other cases are more complicated. Maybe your solution works for one set of inputs, but not for another. So always read the instructions and test your output carefully. There will almost certainly be a sign of an error. - - However, if you're sure there's an error or find some kind of inaccuracy, you can always point it out. At the end of each theory section, there's a link to the contents of the lesson on Github (this project is completely open-source!). You can write about an issue, look through the tests (you can see how your code is called there), and even send a pull request. If this still feels like a dark forest for you, then join our community, we'll always be there to help in the _#hexlet-feedback_ channel. - - -instructions: | - Display `9780262531962`. - -definitions: - - name: Tests - description: | - are special code that checks the programs have been made correctly by checking the correct result against the actual one. - -tips: - - | - [TDD](https://en.wikipedia.org/wiki/Test-driven_development) diff --git a/modules/10-basics/45-testing/description.ru.yml b/modules/10-basics/45-testing/description.ru.yml deleted file mode 100644 index cd24ed7c..00000000 --- a/modules/10-basics/45-testing/description.ru.yml +++ /dev/null @@ -1,49 +0,0 @@ ---- - -name: Как мы проверяем ваши решения -theory: | - - Наш сайт автоматически проверяет ваши решения. Как это работает? - - В самом простом случае, система просто запускает код и смотрит на то, что вывелось на экран. А потом сверяет с тем, что мы «ожидали» по заданию. - - В следующих, более сложных уроках, вы будете писать функции — мини-программы, принимающие информацию из внешнего мира и производящие какие-то операции. Проверка ваших решений в таких случаях выглядит немного сложнее: система запускает ваше решение и передаёт какую-то информацию. Система также знает — «ожидает» — какой именно ответ должна дать правильная функция при таких входных данных. - - Например, если ваша задача — написать функцию сложения двух чисел, то проверочная система будет передавать ей разные комбинации чисел и сверять ответ вашей функции с реальными суммами. Если во всех случаях ответы совпадут, то решение считается верным. - - Такой подход называется тестированием, и он используется в реальной повседневной разработке. Обычно программист сначала пишет тест — проверочную программу, а потом уже ту программу, которую хотел написать. В процессе он постоянно запускает тесты и смотрит, приблизился ли он к решению. - - Именно поэтому наш сайт говорит «Тесты пройдены», когда вы правильно решили задачу. - - Вот простой пример: необходимо распечатать строку `Hello, World!`. Предположим, вы допустили небольшую ошибку, и функция вывела на экран другое значение. Система ответит примерно так: - -
-    -'Hello, World!'
-    +'ello, World!'
-
-    FAILURES!
-    Tests: 1, Assertions: 1, Failures: 1.
-  
- - На экране появляется подсказка. На ней знаком `+` обозначено то, что распечатал ваш код. Знаком `-` – то, что ожидалось. Сравнивая эти два значения, можно увидеть ошибку. В примере выше видно, что в выводе пропущена буква _H_. - - Кроме наших тестов, будет крайне полезно экспериментировать с кодом. Для этого можно использовать сервис [repl.it](https://repl.it/languages/php). Идеально, если вы выполните самостоятельно весь код, который присутствует в уроках. - - --- - - Иногда в процессе решения будет казаться, что вы сделали все правильно, но система «капризничает» и не принимает решение. Подобное поведение практически исключено. Нерабочие тесты просто не могут попасть на сайт, они автоматически запускаются после каждого изменения. В подавляющем большинстве таких случаев, (а все наши проекты в сумме провели миллионы проверок за много лет), ошибка содержится в коде решения. Она может быть очень незаметной, вместо английской буквы случайно ввели русскую, вместо верхнего регистра использовали нижний или забыли вывести запятую. Другие случаи сложнее. Возможно ваше решение работает для одного набора входных данных, но не работает для другого. Поэтому всегда внимательно читайте условие задачи и вывод тестов. Там почти наверняка есть указание на ошибку. - - Однако, если вы уверены в ошибке или нашли какую-то неточность, то вы всегда можете указать на неё. В конце каждой теории есть ссылка на содержимое урока на гитхабе (этот проект полностью открытый!). Перейдя туда, вы можете написать issue, посмотреть содержимое тестов (там видно, как вызывается ваш код) и даже отправить pullrequest. Если для вас это пока тёмный лес, то подключитесь в наше сообщество [Telegram Hexlet](https://t.me/hexletcommunity/12), там в канале Волонтеры мы всегда поможем. - - -instructions: | - Выведите на экран `9780262531962`. - -definitions: - - name: Тесты - description: | - специальный код, проверяющий программы на корректность, сверяя правильный результат с реальным. - -tips: - - | - [TDD](https://ru.wikipedia.org/wiki/Разработка_через_тестирование) diff --git a/modules/10-basics/45-testing/en/data.yml b/modules/10-basics/45-testing/en/data.yml index afbc8565..2e46678c 100644 --- a/modules/10-basics/45-testing/en/data.yml +++ b/modules/10-basics/45-testing/en/data.yml @@ -1,3 +1,4 @@ +--- name: How we test your solutions definitions: - name: Tests diff --git a/modules/10-basics/45-testing/es/data.yml b/modules/10-basics/45-testing/es/data.yml index 3d67a446..c5c4a247 100644 --- a/modules/10-basics/45-testing/es/data.yml +++ b/modules/10-basics/45-testing/es/data.yml @@ -1,3 +1,4 @@ +--- name: Cómo verificamos tus soluciones definitions: - name: Pruebas diff --git a/modules/10-basics/45-testing/ru/data.yml b/modules/10-basics/45-testing/ru/data.yml index 9245d42b..72d8e83f 100644 --- a/modules/10-basics/45-testing/ru/data.yml +++ b/modules/10-basics/45-testing/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Как мы проверяем ваши решения definitions: - name: Тесты diff --git a/modules/10-basics/50-syntax-errors/description.en.yml b/modules/10-basics/50-syntax-errors/description.en.yml deleted file mode 100644 index dc4701c3..00000000 --- a/modules/10-basics/50-syntax-errors/description.en.yml +++ /dev/null @@ -1,33 +0,0 @@ ---- - -name: Syntax errors -theory: | - If a PHP program is written syntactically incorrectly, the interpreter will display a corresponding message on the screen, along with a pointer to the file and line where it thinks the error occurred. _Syntax errors_ occur when the code has grammatical mistakes. Grammar is essential to human language, but a text with grammar mistakes can still be read and understood. However, when it comes to programming, things are much more strict. Any tiny violation and the program won't even start. Maybe you've mixed up your brackets, or there's a `;`, that you forgot to add — these are just some examples of such mistakes. - - Here is an example of some code with a syntax error: - - ```php - - 7 - - - Besides addition, we can also use the following operations: - - * `*` — multiplication - * `/` — division - * `-` — subtraction - * `%` — [remainder](https://en.wikipedia.org/wiki/Euclidean_division) - * `**` — exponentiation - - Now let’s print the result of a division, and then the result of an exponentiation: - - ```php - 4 - print_r(3 ** 2); // => 9 - ``` - - Sometimes, for convenience, we'll show the result of running lines of code in the comments like this: `=> RESULT`. For example, `// => 4`. - - The first statement will print `4` (since 8 / 2 is 4), and the second statement will print 9 (since 32 is 9). - -instructions: | - - Divide `81` by `9` and display the result. - -tips: - - | - Always indent arithmetic operators with spaces between the numbers (operands). It's good form when programming. Therefore, in our examples, we have `print_r(3 + 4)` rather than `print_r(3+4)`. - - | - Dividing by zero causes, unsurprisingly, a `Division by zero` error. To avoid it, you need to know about conditional constructs (you'll learn about them in future - - | - Type your code between the`// BEGIN` and `// END` lines in the editor. diff --git a/modules/20-arithmetics/20-basic/description.ru.yml b/modules/20-arithmetics/20-basic/description.ru.yml deleted file mode 100644 index 19226842..00000000 --- a/modules/20-arithmetics/20-basic/description.ru.yml +++ /dev/null @@ -1,50 +0,0 @@ ---- - -name: Арифметические операции -theory: | - На базовом уровне компьютеры оперируют только числами. Для сложения двух чисел в математике мы пишем, например, `3 + 4`. В программировании — то же самое. В этом уроке разберем, как проводить арифметические операции в коде. - - ## Арифметика в программировании - - Рассмотрим пример программы, которая складывает два числа: - - ```php - 7 - ``` - - Кроме сложения доступны следующие операции: - - * `*` — умножение - * `/` — деление - * `-` — вычитание - * `%` — [остаток от деления](https://ru.wikipedia.org/wiki/Деление_с_остатком) - * `**` — возведение в степень - - Эти знаки операций называют операторами. - -instructions: | - Выведите на экран результат деления числа `81` на `9`. - -tips: - - | - Всегда отбивайте арифметические операторы пробелами от самих чисел (операндов) – это хороший стиль программирования. Поэтому в наших примерах `print_r(3 + 4)`, а не `print_r(3+4)`. - - | - Деление на ноль приводит к ошибке `Division by zero`. Чтобы его не допустить, нужно знать про условные конструкции (о них вы узнаете в следующих уроках). - - | - Если в редакторе есть запись `// BEGIN` и `// END`, то код нужно писать между этими строчками. diff --git a/modules/20-arithmetics/20-basic/en/data.yml b/modules/20-arithmetics/20-basic/en/data.yml index a698198e..b49ab6d9 100644 --- a/modules/20-arithmetics/20-basic/en/data.yml +++ b/modules/20-arithmetics/20-basic/en/data.yml @@ -1,3 +1,4 @@ +--- name: Arithmetic Operations tips: - > @@ -7,6 +8,6 @@ tips: - > Dividing by zero causes, unsurprisingly, a `Division by zero` error. To avoid it, you need to know about conditional constructs (you'll learn about - them in future + them in future - | Type your code between the`// BEGIN` and `// END` lines in the editor. diff --git a/modules/20-arithmetics/20-basic/es/data.yml b/modules/20-arithmetics/20-basic/es/data.yml index 2b87bfdf..e4924e61 100644 --- a/modules/20-arithmetics/20-basic/es/data.yml +++ b/modules/20-arithmetics/20-basic/es/data.yml @@ -1,3 +1,4 @@ +--- name: Operaciones aritméticas tips: - > diff --git a/modules/20-arithmetics/20-basic/ru/data.yml b/modules/20-arithmetics/20-basic/ru/data.yml index e77a18ba..0333794a 100644 --- a/modules/20-arithmetics/20-basic/ru/data.yml +++ b/modules/20-arithmetics/20-basic/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Арифметические операции tips: - > diff --git a/modules/20-arithmetics/25-operator/description.en.yml b/modules/20-arithmetics/25-operator/description.en.yml deleted file mode 100644 index 69ab7e40..00000000 --- a/modules/20-arithmetics/25-operator/description.en.yml +++ /dev/null @@ -1,59 +0,0 @@ ---- - -name: Operators -theory: | - - Before we move on, let's take a look at the basic terminology. An operation sign, such as `+`, is called an **operator**. Operators perform operations on certain values, which are called **operands**. The operators themselves are usually represented by one or more characters,, and occasionally by a word. Most of the operators are identical to those you'll have seen in math class. - - ```php - -3 - ``` - - Above is an example of applying a unary operation to the number `3`. The minus operator before the three tells the interpreter to take the number `3` and find the opposite, which is `-3`. - - This can be a bit confusing because `-3` is both a number in itself and an operator with an operand, but this is just how programming languages are structured. - - ```php - 1 - ``` - - The same goes for the plus sign: - - ```php - 3 - print_r(1 + +3); // => 4 - ``` - -instructions: | - Write a program that calculates the difference between the numbers `6` and `-81` and displays the answer on the screen. - -tips: - - | - [Operators in PHP](https://www.php.net/manual/en/language.operators.php) - -definitions: - - name: "Arithmetic operations" - description: "include addition, subtraction, multiplication and division." - - name: "A unary operation" - description: "is an operation with one operand. For example, `-3` is a unary operation to get the opposite of three." - - name: "A binary operation" - description: "is an operation with two operands. For example, `3 + 9`." diff --git a/modules/20-arithmetics/25-operator/description.ru.yml b/modules/20-arithmetics/25-operator/description.ru.yml deleted file mode 100644 index c9520739..00000000 --- a/modules/20-arithmetics/25-operator/description.ru.yml +++ /dev/null @@ -1,62 +0,0 @@ ---- - -name: Операторы -theory: | - Знак операции, например, `+`, называют **оператором**. Операторы обычно представлены одним или несколькими символами, реже — словом. Обычно они соответствуют математическим операциям. - - Операторы выполняют операции над определенными значениями, которые называются **операндами**. - - Рассмотрим пример: - - ```php - -3 - ``` - - Выше пример применения унарной операции к числу `3`. Оператор `-` перед тройкой говорит интерпретатору взять число `3` и найти противоположное, то есть `-3`. Это может сбить с толку, потому что `-3` — это одновременно и число, и оператор с операндом. Но у языков программирования такая структура: - - ```php - 1 - ``` - - То же самое касается и плюса: - - ```php - 3 - print_r(1 + +3); // => 4 - ``` - -instructions: | - Напишите программу, которая посчитает разность между числами `6` и `-81` и выведет ответ на экран. - -tips: - - | - [Операторы в PHP](https://www.php.net/manual/ru/language.operators.php) - -definitions: - - name: "Арифметическая операция" - description: "сложение, вычитание, умножение и деление." - - name: "Унарная операция" - description: "операция с одним операндом. Например, `-3` — унарная операция для получения числа, противоположного числу три." - - name: "Бинарная операция" - description: "операция с двумя операндами. Например, `3 + 9`." diff --git a/modules/20-arithmetics/25-operator/en/data.yml b/modules/20-arithmetics/25-operator/en/data.yml index 4d82fa82..97c08277 100644 --- a/modules/20-arithmetics/25-operator/en/data.yml +++ b/modules/20-arithmetics/25-operator/en/data.yml @@ -1,3 +1,4 @@ +--- name: Operators tips: - | diff --git a/modules/20-arithmetics/25-operator/es/data.yml b/modules/20-arithmetics/25-operator/es/data.yml index f2395a67..b293f4c9 100644 --- a/modules/20-arithmetics/25-operator/es/data.yml +++ b/modules/20-arithmetics/25-operator/es/data.yml @@ -1,3 +1,4 @@ +--- name: Operadores tips: - | diff --git a/modules/20-arithmetics/25-operator/ru/data.yml b/modules/20-arithmetics/25-operator/ru/data.yml index b353e864..c1529fbb 100644 --- a/modules/20-arithmetics/25-operator/ru/data.yml +++ b/modules/20-arithmetics/25-operator/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Операторы tips: - | diff --git a/modules/20-arithmetics/27-commutativity/description.en.yml b/modules/20-arithmetics/27-commutativity/description.en.yml deleted file mode 100644 index 39e6ceb4..00000000 --- a/modules/20-arithmetics/27-commutativity/description.en.yml +++ /dev/null @@ -1,24 +0,0 @@ ---- - -name: Commutative operation -theory: | - Do you remember the basic rule of arithmetic that changing the order of the numbers we're adding doesn't change the sum? It's one of the most basic and intuitive rules of arithmetics, it's called the **commutative law**. - - A binary operation is considered commutative if you get the same result after swapping operands. Obviously, addition is a commutative operation: _3 + 2 = 2 + 3_. - - But is subtraction a commutative operation? Of course not: _2 - 3 ≠ 3 - 2_. In programming, this law applies in the same way as in arithmetic. - - Moreover, most of the operations we face in real life aren't commutative. In conclusion, you should always pay attention to the order of things you're working with. - -instructions: | - - Write a program that counts and sequentially displays the values of the following mathematical expressions: "3 to the power of 5" and "-8 divided by -4". - - Note that the results will appear stuck together, on one line, and without any spaces. We'll learn how to deal with this problem in future lessons. - -tips: [] - -definitions: - - name: Commutativity - description: | - is the property of an operation wherein changing the order of operands doesn't affect the result. For example, addition is a commutative operation; changing the order of the numbers we're adding doesn't change the result. diff --git a/modules/20-arithmetics/27-commutativity/description.ru.yml b/modules/20-arithmetics/27-commutativity/description.ru.yml deleted file mode 100644 index bb18c980..00000000 --- a/modules/20-arithmetics/27-commutativity/description.ru.yml +++ /dev/null @@ -1,19 +0,0 @@ ---- - -name: Коммутативная операция -theory: | - В программировании используется базовый закон арифметики: от перемены мест слагаемых сумма не меняется. Он называется **коммутативным законом**. Если поменять местами операнды в бинарной операции, и получится тот же результат, такая операция будет коммутативной. Получается, что сложение — коммутативная операция: `3 + 2 = 2 + 3`. - - Вычитание не будет являться коммутативной операцией: `2 - 3 ≠ 3 - 2`. В программировании этот закон тоже работает. Большинство операций, с которыми мы будем сталкиваться в реальной жизни, не являются коммутативными. Поэтому всегда нужно обращать внимание на порядок того, с чем работаем. - -instructions: | - Напишите программу, которая считает и последовательно выводит на экран значения следующих математических выражений: «3 в степени 5» и «-8 разделить на -4». - - Обратите внимание, что результаты выведутся «слепленными» в одну строчку без пробела. Мы научимся решать эту проблему в будущих уроках. - -tips: [] - -definitions: - - name: Коммутативность - description: | - свойство операции, когда изменение порядка операндов не влияет на результат. Например, сложение — коммутативная операция: от перемены мест слагаемых сумма не меняется. diff --git a/modules/20-arithmetics/27-commutativity/en/data.yml b/modules/20-arithmetics/27-commutativity/en/data.yml index 2b152f67..2c089090 100644 --- a/modules/20-arithmetics/27-commutativity/en/data.yml +++ b/modules/20-arithmetics/27-commutativity/en/data.yml @@ -1,3 +1,4 @@ +--- name: Commutative operation tips: [] definitions: diff --git a/modules/20-arithmetics/27-commutativity/es/data.yml b/modules/20-arithmetics/27-commutativity/es/data.yml index 2443694a..e35e77e9 100644 --- a/modules/20-arithmetics/27-commutativity/es/data.yml +++ b/modules/20-arithmetics/27-commutativity/es/data.yml @@ -1,3 +1,4 @@ +--- name: Operación conmutativa tips: [] definitions: diff --git a/modules/20-arithmetics/27-commutativity/ru/data.yml b/modules/20-arithmetics/27-commutativity/ru/data.yml index d6004c26..30c686eb 100644 --- a/modules/20-arithmetics/27-commutativity/ru/data.yml +++ b/modules/20-arithmetics/27-commutativity/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Коммутативная операция tips: [] definitions: diff --git a/modules/20-arithmetics/30-composition/description.en.yml b/modules/20-arithmetics/30-composition/description.en.yml deleted file mode 100644 index 44eb5527..00000000 --- a/modules/20-arithmetics/30-composition/description.en.yml +++ /dev/null @@ -1,41 +0,0 @@ ---- - -name: Composition of operations -theory: | - Suppose we want to calculate an expression like `3 * 5 - 2`? This is how we'd write it down: - - ```php - 13 - ``` - - Note that the interpreter performs arithmetic operations in the right order: first division and multiplication, then addition and subtraction. Sometimes we want to change the order of operations. We'll dig into this topic in the next lesson. - - Or another example: - - ```php - 400 - ``` - - We can combine operations, which allows us to calculate even more complex compound expressions. This property of operations is called composition. The composition of arithmetic operations in programming is similar to how it's done in school. As you'll later learn, the composition of operations applies to all operations in general, not just arithmetic operations. - - To visualize how calculations are done inside the interpreter, let's look at an example: `2 * 4 * 5 * 10`. - - 1. First we calculate `2 * 4` and get `8 * 5 * 10`. - 1. Then `8 * 5`. The result is `40 * 10`. - 3. Finally, we do the last multiplication, and the result is `400`. - -instructions: | - - Write a program that calculates and prints the value of this expression: - - ``` - 8 / 2 + 5 - -3 / 2 - ``` - - Don't calculate anything manually, your program should do all the calculations on its own. - -# tips: [] diff --git a/modules/20-arithmetics/30-composition/description.ru.yml b/modules/20-arithmetics/30-composition/description.ru.yml deleted file mode 100644 index 8522b2f0..00000000 --- a/modules/20-arithmetics/30-composition/description.ru.yml +++ /dev/null @@ -1,32 +0,0 @@ ---- - -name: Композиция операций -theory: | - Разберем пример композиции операций: - - ```php - 400 - ``` - - Операции можно соединять друг с другом. Это дает возможность вычислять более сложные составные выражения. Такое свойство операций называется **композицией**. - - Композиция арифметических операций в программировании аналогична композиции из школьной программы. Она распространяется на все операции, а не только на арифметические. - - Чтобы представить, как происходят вычисления внутри интерпретатора, разберем пример: `2 * 4 * 5 * 10`. - - 1. Сначала вычисляется `2 * 4` и получается выражение `8 * 5 * 10` - 2. Затем `8 * 5`. В итоге имеем `40 * 10` - 3. В конце происходит последнее умножение, и получается результат `400` - -instructions: | - Реализуйте программу, которая вычисляет и выводит на экран значение выражения: - - ``` - 8 / 2 + 5 - -3 / 2 - ``` - - Не вычисляйте ничего самостоятельно, ваша программа должна производить все вычисления сама. - -tips: [] diff --git a/modules/20-arithmetics/30-composition/en/data.yml b/modules/20-arithmetics/30-composition/en/data.yml index 54ecc5cb..dd845543 100644 --- a/modules/20-arithmetics/30-composition/en/data.yml +++ b/modules/20-arithmetics/30-composition/en/data.yml @@ -1 +1,2 @@ +--- name: Composition of operations diff --git a/modules/20-arithmetics/30-composition/es/data.yml b/modules/20-arithmetics/30-composition/es/data.yml index ee2fdfce..67887cb0 100644 --- a/modules/20-arithmetics/30-composition/es/data.yml +++ b/modules/20-arithmetics/30-composition/es/data.yml @@ -1,2 +1,3 @@ +--- name: Composición de operaciones tips: [] diff --git a/modules/20-arithmetics/30-composition/ru/data.yml b/modules/20-arithmetics/30-composition/ru/data.yml index da230c59..bcab44d9 100644 --- a/modules/20-arithmetics/30-composition/ru/data.yml +++ b/modules/20-arithmetics/30-composition/ru/data.yml @@ -1,2 +1,3 @@ +--- name: Композиция операций tips: [] diff --git a/modules/20-arithmetics/40-priority/description.en.yml b/modules/20-arithmetics/40-priority/description.en.yml deleted file mode 100644 index 7bd11155..00000000 --- a/modules/20-arithmetics/40-priority/description.en.yml +++ /dev/null @@ -1,52 +0,0 @@ ---- - -name: Priority of operations -theory: | - Look closely at the expression `2 + 2 * 2` and try and work out the answer. - - The correct answer is `6`. - - If you got `8`, then this lesson is for you. You'll have studied the order of operations in high school math. This concept defines the order in which operations are to be performed. For example, multiplication and division have a higher precedence than addition and subtraction, and exponentiation comes before all other arithmetic operations, e.g., `2 ** 3 * 2` gives us `16`. - - But sometimes, we have to perform calculations in a non-standard order. In complex cases, precedence can (and must) be set with parentheses, just like we did in high school, e.g, `(2 + 2) * 2`. - - Parentheses fit with any operation. They can be nested into each other as many times as you need. Here are a couple of examples: - - ```php - 9 - print_r(7 * 3 + (4 / 2) - (8 + (2 - 1))); // => 14 - ``` - - The main thing is to make sure to close the parentheses in the correct order. This often causes errors not just for beginners but also for experienced programmers. For convenience's sake, do the opening and closing parentheses first, and then write the inside part. The editor on our site (and most other code editors) does this automatically: you write `(`, and the editor immediately adds `)`. This also applies to other paired characters, such as quotation marks. We'll talk about them in future lessons. - - Sometimes, an expression can be visually cumbersome. In such cases, parentheses can come in handy without affecting the order of operations. For example, the task from the previous lesson gets clearer if you have parentheses. - - Before: - - ```php - 10.5 - ``` - - After: - - ```php - 10.5 - ``` - - Note: code is written for humans, since they'll be the ones to read it, the machine just executes it. For the machine, code is either valid or invalid, it doesn't recognize "more" or "less" valid code. Explicit prioritization makes it easier for other developers to read your code. - -instructions: | - - Here's a calculation: `70 * 3 + 4 / 8 + 2`. - - Place parentheses so that both additions, (`3 + 4`) and (`8 + 2`) will be calculated first. Print the result on the screen. - -tips: - - | - [Priority of operators](https://www.php.net/manual/en/language.operators.precedence.php) diff --git a/modules/20-arithmetics/40-priority/description.ru.yml b/modules/20-arithmetics/40-priority/description.ru.yml deleted file mode 100644 index 9160107f..00000000 --- a/modules/20-arithmetics/40-priority/description.ru.yml +++ /dev/null @@ -1,39 +0,0 @@ ---- - -name: Приоритет операций -theory: | - В школьной математике есть понятие «приоритет операции». Приоритет определяет, в какой последовательности должны выполняться операции. - - Допустим, нам нужно вычислить такое выражение: `2 + 2 * 2`: - - ```php - 6 - ``` - - Интерпретатор производит арифметические вычисления в правильном порядке: сначала деление и умножение, потом сложение и вычитание, а приоритет возведения в степень выше всех остальных арифметических операций: `2 ** 3 * 2` вычислится в `16`. - - Иногда вычисления должны происходить в другом порядке. В этом случае приоритет задают круглыми скобками, например: `(2 + 2) * 2`. Скобки можно ставить вокруг любой операции. Они могут вкладываться друг в друга сколько угодно раз. Вот пара примеров: - - ```php - 9 - print_r(7 * 3 + (4 / 2) - (8 + (2 - 1))); // => 14 - ``` - - В этом случае главное закрывать скобки в правильном порядке. Это часто становится причиной ошибок не только у новичков, но и у опытных программистов. Для удобства можно сразу ставить открывающую и закрывающую скобки, а потом писать внутреннюю часть. - - Сейчас большинство редакторов кода делают это автоматически. Например, мы ставим открывающую скобку, а он автоматически ставит закрывающую. Это касается и других парных символов, например, кавычек. О них — в будущих уроках. - - Иногда выражение сложно воспринимать визуально. Тогда можно расставить скобки, не повлияв на приоритет. Код пишется для людей, а машины будут только исполнять его. Для машин код — или корректный, или не корректный. Для них нет «более» понятного или «менее» понятного кода. Явная расстановка приоритетов упрощает чтение кода другими разработчиками. - -instructions: | - Дано вычисление `70 * 3 + 4 / 8 + 2`. - - Расставьте скобки так, чтобы оба сложения (`3 + 4`) и (`8 + 2`) высчитывались в первую очередь. Выведите на экран результат. - -tips: - - | - [Приоритет операторов](https://www.php.net/manual/ru/language.operators.precedence.php) diff --git a/modules/20-arithmetics/40-priority/en/data.yml b/modules/20-arithmetics/40-priority/en/data.yml index 7267426e..ccbfb007 100644 --- a/modules/20-arithmetics/40-priority/en/data.yml +++ b/modules/20-arithmetics/40-priority/en/data.yml @@ -1,3 +1,4 @@ +--- name: Priority of operations tips: - > diff --git a/modules/20-arithmetics/40-priority/es/data.yml b/modules/20-arithmetics/40-priority/es/data.yml index c4ccc1a8..55a001b9 100644 --- a/modules/20-arithmetics/40-priority/es/data.yml +++ b/modules/20-arithmetics/40-priority/es/data.yml @@ -1,3 +1,4 @@ +--- name: Prioridad de las operaciones tips: - > diff --git a/modules/20-arithmetics/40-priority/ru/data.yml b/modules/20-arithmetics/40-priority/ru/data.yml index df7a9915..84df3bea 100644 --- a/modules/20-arithmetics/40-priority/ru/data.yml +++ b/modules/20-arithmetics/40-priority/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Приоритет операций tips: - > diff --git a/modules/20-arithmetics/45-linting/description.en.yml b/modules/20-arithmetics/45-linting/description.en.yml deleted file mode 100644 index 68748296..00000000 --- a/modules/20-arithmetics/45-linting/description.en.yml +++ /dev/null @@ -1,47 +0,0 @@ ---- - -name: Linter -theory: | - Since we've learned to write simple programs, let's talk about the very process of writing. - - Code must be designed in a certain way so that it's clear and easy to maintain. Special sets of rules - standards - describe different aspects of code writing. Specifically in PHP, the most common standards are the **PSR** standards (PHP Standards Recommendations) from [PHP-FIG](https://www.php-fig.org/psr/). A recommendation is a set of rules designed to facilitate a particular aspect of development (or to solve a particular problem). Currently there are several approved recommendations, each labeled with a number: PSR-1, PSR-2, PSR-3 and [so on](https://en.wikipedia.org/wiki/PHP_Standard_Recommendation). You'll gradually become familiar with all of these recommendations as you learn and work. Now let's focus on the two main ones: - - * PSR-1: [Basic Coding Standard](https://www.php-fig.org/psr/psr-1/). This is a set of rules defining how to write PHP code, including how to write PHP tags, and what rules to use for naming classes, methods and class constants. It also touches on encoding, autoloading, namespaces, and sharing responsibility between files. These are basic rules; the PSR-12 standard expands on them. - * PSR-12: [Extended Coding Style](https://www.php-fig.org/psr/psr-12/). replaces and supplements the obsolete PSR-2. The first thing to mention is that this standard requires compliance with PSR-1 rules. Secondly, it adds many new requirements, for indentations, files, strings, keywords, classes, control structures, scope and other elements. - - In any programming language, there are special tools, called **linters**, which check the code for compliance with standards. One commonly used linter in PHP is the [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer). - - Suppose we have a file with this PHP code: - - ```php - - ``` - - When you check the file, the linter will find the following errors: - - * `Spaces must be used to indent lines; tabs are not allowed` — PSR-12 recommends indenting four spaces, and the example above uses tabs - * `A closing tag is not permitted at the end of a PHP file` — the standard requires the closing tag `?>` - * `Space before opening parenthesis of function call prohibited` — when calling a function, there should be no whitespace between the function name and parentheses, and in the code being checked there is one space after `print_r` name - - Fix the code by removing the closing tag, indentation, and space after the function name: - - ```php - 10.5 - ``` - - This code doesn't violate the rules, and the linter will "say nothing", as it were. - - Don't be frightened by the abundance of recommendations and rules. Most of the rules are simple and straightforward. You'll most likely intuitively stick to them in the code anyway. Time, experience, and a linter will help you with the rest ;) - -instructions: | - - Print the result of the difference between five squared and the product of three and seven. Write the code so that each operator is separated from the operands with spaces. - -# tips: [] diff --git a/modules/20-arithmetics/45-linting/description.ru.yml b/modules/20-arithmetics/45-linting/description.ru.yml deleted file mode 100644 index d0af2c25..00000000 --- a/modules/20-arithmetics/45-linting/description.ru.yml +++ /dev/null @@ -1,53 +0,0 @@ ---- - -name: Линтер -theory: | - В этом уроке мы узнаем, что такое стандарты по написанию кода. Они облегчают разработку и делают код более понятным. Мы подробнее разберем две основные рекомендации по PHP, которые содержат правила по написанию кода. - - ## Стандарты по написанию кода в PHP - - Код нужно оформлять так, чтобы он был понятным и простым в поддержке. Для этого существуют специальные наборы правил — **стандарты**. Они описывают различные аспекты написания кода. - - В PHP самыми распространенными являются стандарты **PSR** — PHP Standards Recommendations или стандартные рекомендации PHP от [PHP-FIG](https://www.php-fig.org/psr/). Это набор правил, которые облегчают разработку и решают определенную проблему. - - На текущий момент существует несколько утвержденных рекомендаций, каждая из них обозначена цифрой: PSR-1, PSR-2, PSR-3 и [другие](https://en.wikipedia.org/wiki/PHP_Standard_Recommendation). Со всеми рекомендациями вы познакомитесь во время обучения и работы. - В этом уроке разберем подробнее следующие: - - * PSR-1. [Basic Coding Standard](https://www.php-fig.org/psr/psr-1/) — базовый стандарт написания кода. Это набор правил, которые определяют, как следует оформлять программный код: как писать теги PHP, по каким правилам именовать классы, методы и константы классов. Он также затрагивает вопросы кодировки, автозагрузки, пространства имен и разделения ответственности между файлами - * PSR-12. [Extended Coding Style](https://www.php-fig.org/psr/psr-12/) — расширенный стандарт стиля кодирования, заменяет и дополняет устаревший PSR-2. Этот стандарт требует выполнения правил PSR-1. Также он добавляет множество новых требований: к отступам, файлам, строкам, ключевым словам, классам, управляющим конструкциям, области видимости и другим элементам - - ## Линтеры в PHP - - В любом языке программирования существуют специальные инструменты — **линтеры**. Они проверяют код на соответствие стандартам. Повсеместно используемым линтером в PHP является [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer). - - Допустим, у нас есть файл с таким PHP-кодом: - - ```php - - ``` - - При проверке файла линтер найдет следующие ошибки: - - * `Spaces must be used to indent lines; tabs are not allowed` — PSR-12 рекомендует делать отступ размером в четыре пробела, а в примере выше использована табуляция - * `A closing tag is not permitted at the end of a PHP file` — стандарт содержит требование опускать завершающий тег `?>` - * `Space before opening parenthesis of function call prohibited` — при вызове функции между именем функции и круглыми скобками не должно быть пробельных символов, а в проверяемом коде после имени `print_r` стоит один пробел - - Исправим код — уберем закрывающий тег, отступы и пробел после имени функции: - - ```php - 10.5 - ``` - - Этот вариант уже не нарушает правил, и линтер будет «молчать». - -instructions: | - Выведите на экран результат следующего вычисления: «разница между пятью в квадрате и произведением трёх и семи». Напишите код так, чтобы каждый оператор отделялся от операндов пробелами. - -tips: [] diff --git a/modules/20-arithmetics/45-linting/en/data.yml b/modules/20-arithmetics/45-linting/en/data.yml index 5dcbe414..61228d5c 100644 --- a/modules/20-arithmetics/45-linting/en/data.yml +++ b/modules/20-arithmetics/45-linting/en/data.yml @@ -1 +1,2 @@ +--- name: Linter diff --git a/modules/20-arithmetics/45-linting/es/data.yml b/modules/20-arithmetics/45-linting/es/data.yml index d14182b1..aabf032d 100644 --- a/modules/20-arithmetics/45-linting/es/data.yml +++ b/modules/20-arithmetics/45-linting/es/data.yml @@ -1,2 +1,3 @@ +--- name: Linter tips: [] diff --git a/modules/20-arithmetics/45-linting/ru/data.yml b/modules/20-arithmetics/45-linting/ru/data.yml index d3e5043c..2dd0d71d 100644 --- a/modules/20-arithmetics/45-linting/ru/data.yml +++ b/modules/20-arithmetics/45-linting/ru/data.yml @@ -1,2 +1,3 @@ +--- name: Линтер tips: [] diff --git a/modules/25-strings/10-quotes/description.en.yml b/modules/25-strings/10-quotes/description.en.yml deleted file mode 100644 index 65427d50..00000000 --- a/modules/25-strings/10-quotes/description.en.yml +++ /dev/null @@ -1,112 +0,0 @@ ---- - -name: Quotes -theory: | - - ```php - 'Hello' - 'Goodbye' - - 'G' - ' ' - '' - ``` - - Which of these five items are strings? - - With the first two, everything is clear, they're strings, we've already worked with similar constructions and said that strings are sets of characters. - - Any single character between parentheses is a string. `''`, is also a string (albeit empty). So everything inside the quotation marks can be considered a string, even if it's a space, one character, or no characters at all. - - In previous lessons, we enclosed strings in single quotes. You can also use double quotes: - - ```php - Dragon's mother said "No" - ``` - - Look closely: we had to use `\` for double quotes to escape them, and not for the single quote (apostrophe) because the string is written in double quotes. If the string were written in single quotes, the escape character would be used before the apostrophe, not before the double quotes. - - ```php - Death is \so terribly final - ``` - - But what if you want to print the backslash? Just like any other special symbol, it escapes using a backslash too. - - ```php - \ - ``` - - Self-test: what will be printed? - - ```php - - "Khal Drogo's favorite word is "athjahakar"" - - -tips: [] diff --git a/modules/25-strings/10-quotes/description.ru.yml b/modules/25-strings/10-quotes/description.ru.yml deleted file mode 100644 index d936f9ce..00000000 --- a/modules/25-strings/10-quotes/description.ru.yml +++ /dev/null @@ -1,110 +0,0 @@ ---- - -name: Кавычки -theory: | - В этом уроке мы разберем, что такое строки, зачем для них нужны одинарные и двойные кавычки. Также узнаем, что такое экранирующие последовательности и конкатенация. - - ## Что такое строка - - Любой одиночный символ в кавычках — это **строка**. Например: - - ```php - 'Hello' - 'Goodbye' - 'G' - ' ' - '' - ``` - - Пустая строка `''` — это тоже строка. То есть строкой мы считаем все, что находится внутри кавычек, даже если это пробел, один символ или вообще отсутствие символов. - - Ранее в уроках мы записывали строки в одинарных кавычках, но можно использовать и двойные: - - ```php - Dragon's mother said "No" - ``` - - Нам нужно было добавить `\` для двойных кавычек, но не для апострофа, потому что сама строка создана с двойными кавычками. Если бы строка создавалась с одинарными кавычками, то символ экранирования нужен был бы перед апострофом, но не перед двойными кавычками. - - ```php - Death is \so terribly final - ``` - - Также нам может понадобиться вывести сам обратный слеш: - - ```php - \ - ``` - - Это тоже можно сделать через экранирование, но уже самого себя. - -instructions: | - Напишите программу, которая выведет на экран: - - ``` - "Khal Drogo's favorite word is "athjahakar"" - ``` - - Программа должна вывести на экран эту фразу в точности. Обратите внимание на кавычки в начале и в конце фразы: - -
-  "Khal Drogo's favorite word is "athjahakar""
-  
- -tips: [] diff --git a/modules/25-strings/10-quotes/en/data.yml b/modules/25-strings/10-quotes/en/data.yml index 7ce908f5..37db4947 100644 --- a/modules/25-strings/10-quotes/en/data.yml +++ b/modules/25-strings/10-quotes/en/data.yml @@ -1,2 +1,3 @@ +--- name: Quotes tips: [] diff --git a/modules/25-strings/10-quotes/es/data.yml b/modules/25-strings/10-quotes/es/data.yml index 1ceacd43..a61d3800 100644 --- a/modules/25-strings/10-quotes/es/data.yml +++ b/modules/25-strings/10-quotes/es/data.yml @@ -1,2 +1,3 @@ +--- name: Comillas tips: [] diff --git a/modules/25-strings/10-quotes/ru/data.yml b/modules/25-strings/10-quotes/ru/data.yml index e583d868..e8d8642b 100644 --- a/modules/25-strings/10-quotes/ru/data.yml +++ b/modules/25-strings/10-quotes/ru/data.yml @@ -1,2 +1,3 @@ +--- name: Кавычки tips: [] diff --git a/modules/25-strings/15-escape-characters/description.en.yml b/modules/25-strings/15-escape-characters/description.en.yml deleted file mode 100644 index 841779dd..00000000 --- a/modules/25-strings/15-escape-characters/description.en.yml +++ /dev/null @@ -1,142 +0,0 @@ ---- - -name: Escape equences -theory: | - - We want to show a dialogue between the Mother of Dragons and her child: - - ``` - - Are you hungry? - - Aaaarrrgh! - ``` - - If you display a line with this text on the screen: - - ```php - - - Hey!¶ - - Oh, hey!¶ - - How's it going? - - - The device that outputs the corresponding text takes this character into account. For example, the printer pulls the paper up one line when it encounters the LF, and the text editor pulls all subsequent text below, also by one line. - - `\n` is an example of an **escape sequence**. They're also called control constructs. Although there are more than a dozen such characters, there are often only a few such characters in programming. In addition to line feeds, these can include tabs (the break you get when you press the Tab button) and carriage returns (only in Windows). We programmers often need to use line feed `\n` for proper text formatting. - - ```php - - Gregor Clegane - Dunsen - Polliver - Chiswyck - - - Note the following points: - - 1. It does not matter what comes before or after `\n`: a character or an empty string. The line feed will be spotted and executed in any case. - - 2. Remember that a string can contain a single character or zero characters. Also, a string can only contain `\n`. Analyze the following example: - - ```php - - Gregor Clegane - Dunsen - - - 3. If we need to output `\n` as text (two separate printable characters), we can use the escape method we already know, adding another `\` at the beginning. I.e., the sequence `\\n` will appear as the characters `\` and `n` following each other. - - ```php - - Joffrey loves using \n - - - A small but important note about Windows. Windows uses `\r\n`. to do line feeds by default. This combination works well only in Windows, but creates problems when migrating to other systems (for example, when the development team has both Windows and Linux users). The point is that the sequence `\r\n` has a different interpretation depending on the chosen encoding (discussed later). For this reason, it's common among developers to always use `\n` without `\r`, since LF is always treated the same and works fine on any system. Remember to configure your editor to use `\n`. - -instructions: | - - Write a program that prints this to the screen: - - - Did Joffrey agree? - - He did. He also said "I love using \n". - - This program uses only one `print_r()`, but the result on the screen should look exactly like the one shown above. - -definitions: - - name: An escape sequence - description: | - is a special combination of characters in text. For example, `\n` means line feed. - -tips: - - | - Be sure to experiment with the output of different lines on the site [https://repl.it/languages/php](https://repl.it/languages/php) - - | - [History of Line Translation](https://en.wikipedia.org/wiki/Newline) diff --git a/modules/25-strings/15-escape-characters/description.ru.yml b/modules/25-strings/15-escape-characters/description.ru.yml deleted file mode 100644 index cb22a7ad..00000000 --- a/modules/25-strings/15-escape-characters/description.ru.yml +++ /dev/null @@ -1,64 +0,0 @@ ---- - -name: Экранирующие последовательности -theory: | - Иногда нам необходимо расположить несколько строк друг за другом. Для этого нужно сказать интерпретатору «нажать на энтер» — сделать перевод строки после вопросительного знака. Это можно сделать с помощью символа перевода строки — `\n`: - - ```php - Kingswood - - print_r('Kings' . 'road'); // => Kingsroad - - print_r("King's" . 'Landing'); // => King'sLanding - ``` - - As you can see, strings can be concatenated even if they're written in different quotes. - - In the last example, the name of the city has been misspelled: *King's Landing* should be spelled with a space! But there were no spaces in our initial lines, and the spaces in the code itself to the left and right of the `.` character don't matter, because they're not part of the strings. - - There are two ways to fix this: - - ```php - King's Landing - - // Put a space at the start of the right part - print_r("King's" . ' Landing'); // => King's Landing - ``` - - Space is a character like any other, so however many spaces you put in the string is how many you'll get: - - ```php - King's Landing - - print_r("King's " . ' Landing'); // => King's Landing - ``` - -instructions: | - - Print - - ``` - Winter came for the House of Frey. - ``` - - using concatenation - -definitions: - - name: Concatenation - description: | - is the operation of joining two strings. For example, `print_r("King's " . ' Landing');` diff --git a/modules/25-strings/20-strings-concatenation/description.ru.yml b/modules/25-strings/20-strings-concatenation/description.ru.yml deleted file mode 100644 index 858e1ea7..00000000 --- a/modules/25-strings/20-strings-concatenation/description.ru.yml +++ /dev/null @@ -1,63 +0,0 @@ ---- - -name: Конкатенация -theory: | - В веб-разработке программы постоянно оперируют строками. Все, что мы видим на сайтах, так или иначе представлено в виде текста. Этот текст чаще всего динамический — полученный из разных частей, которые соединяются вместе. Операция соединения строк в программировании называется **конкатенацией**. - - Мы уже знаем о математической операции сложения: - - ```php - 8 - ``` - - Такая программа выведет на экран `8` — результат работы бинарного оператора `+` с операндами `5` и `3`. - - Можно также «сложить» две строки. Такая программа выведет на экран `Dragonstone` — результат работы бинарного оператора `.` с операндами 'Dragon' и 'stone': - - ```php - Dragonstone - ``` - - https://replit.com/@hexlet/php-basics-strings-concatenation - - Склеивание строк всегда происходит в том же порядке, в котором записаны операнды. Левый операнд становится левой частью строки, а правый — правой. Вот еще несколько примеров: - - ```php - Kingswood - print_r('Kings' . 'road'); // => Kingsroad - print_r("King's" . 'Landing'); // => King'sLanding - ``` - - Строки можно склеивать, даже если они записаны с разными кавычками. - - Пробел — такой же символ, как и другие, поэтому сколько пробелов поставить в строке — столько и получится в итоговой строке: - - ```php - King's Landing - - // Ставим пробел в правой части - print_r("King's" . ' Landing'); // => King's Landing - ``` - -instructions: | - Выведите на экран - - ``` - Winter came for the House of Frey. - ``` - - используя конкатенацию слов. - -definitions: - - name: Конкатенация - description: | - операция соединения двух строк. Например, `print_r("King's " . ' Landing');` diff --git a/modules/25-strings/20-strings-concatenation/en/data.yml b/modules/25-strings/20-strings-concatenation/en/data.yml index 52b51769..ed2d3886 100644 --- a/modules/25-strings/20-strings-concatenation/en/data.yml +++ b/modules/25-strings/20-strings-concatenation/en/data.yml @@ -1,3 +1,4 @@ +--- name: Concatenation definitions: - name: Concatenation diff --git a/modules/25-strings/20-strings-concatenation/es/data.yml b/modules/25-strings/20-strings-concatenation/es/data.yml index ae3349df..766f42fe 100644 --- a/modules/25-strings/20-strings-concatenation/es/data.yml +++ b/modules/25-strings/20-strings-concatenation/es/data.yml @@ -1,3 +1,4 @@ +--- name: Concatenación definitions: - name: Concatenación diff --git a/modules/25-strings/20-strings-concatenation/ru/data.yml b/modules/25-strings/20-strings-concatenation/ru/data.yml index 1761d6e3..5b4c15a7 100644 --- a/modules/25-strings/20-strings-concatenation/ru/data.yml +++ b/modules/25-strings/20-strings-concatenation/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Конкатенация definitions: - name: Конкатенация diff --git a/modules/25-strings/30-encoding/description.en.yml b/modules/25-strings/30-encoding/description.en.yml deleted file mode 100644 index ec71391c..00000000 --- a/modules/25-strings/30-encoding/description.en.yml +++ /dev/null @@ -1,71 +0,0 @@ ---- - -name: Encoding -theory: | - - At the deepest level, the computer operates exclusively with the numbers `0` and `1`. This is called [binary code](https://en.wikipedia.org/wiki/Binary_code), the ones and zeros are called bits, which is derived from the term "binary digit". - - The numbers that we usually use in the decimal system are encoded using binary numbers: - - - 0 ← 0 - - 1 ← 1 - - 2 ← 10 - - 3 ← 11 - - 4 ← 100 - - 5 ← 101 - - But does it deal with text? The computer isn't aware of letters, punctuation, or other text characters. All these characters are encoded by numbers too. - - We can take the English alphabet and give each letter a number, starting with one: - - - a ← 1 - - b ← 2 - - c ← 3 - - d ← 4 - - ... - - z ← 26 - - This is the essence of **coding**. - - Then you can teach the computer to understand this table and translate text into numbers and vice versa: - - - - `hello` → `8` `5` `12` `12` `15` - - `7` `15` `15` `4` → `good` - - These tables that match letters and numbers are called encodings. Besides letters of the alphabet, encodings include punctuation marks and other useful characters. You've probably encountered encodings such as [ASCII](https://en.wikipedia.org/wiki/ASCII) or [UTF-8](https://en.wikipedia.org/wiki/UTF-8). - - Different encodings contain different numbers of characters. At first, small tables like ASCII were enough for programmers. But it has only Latin letters, a few simple characters like `%` and `?`, and special control characters like line feed. - - As computers became more widespread, different countries needed their own, broader tables. This included Cyrillic letters, Chinese and Japanese characters, Arabic script, additional mathematical and typographic symbols, and later on emojis. - - Today, in most cases, one of the [Unicode](https://en.wikipedia.org/wiki/Unicode) – *utf-8*. It includes characters from almost all the written languages found in the world. Thanks to this, a letter formed by a person in China in Chinese can easily be opened and seen in its original form on a computer in Finland (whether they'll understand it or not is another question). - - Programmers have to deal with encodings regularly. Unicode support in different programming languages is carried out on a different level. Moreover, encodings must be declared when working with databases and files. - - -instructions: | - - In PHP you can "request" and display any ASCII character. For instance: - - ```php - diff --git a/modules/27-data-types/50-data-types-weak-typing/description.en.yml b/modules/27-data-types/50-data-types-weak-typing/description.en.yml deleted file mode 100644 index a23c82b0..00000000 --- a/modules/27-data-types/50-data-types-weak-typing/description.en.yml +++ /dev/null @@ -1,33 +0,0 @@ ---- - -name: Weak typing -theory: | - - We know two different data types: numbers and strings. We could, for example, add numbers, because the addition operation is an operation for the "number" type. - - But what if you add a number to a string? - - ```php - print_r(1 + '7'); // => 8 - ``` - - Although though `'7'` is a string and not a number, the PHP interpreter gave the answer `8`, as if we were adding two numbers. When PHP sees a type mismatch, it tries to convert the information itself. In this case, it converted the string `'7'` to the number `7`, and then happily added `1` and `7`. - - Not all languages can do this. PHP is a language with **weak typing**. It recognizes different data types (numbers, strings, etc.), but doesn't use them too strictly, trying to convert data when it seems reasonable. - - In **strongly typed** languages, adding a number to a string won't work. - - PHP was created for the internet, and on the internet, all information is strings. Even when you type a phone number or a birth year on a website, that information goes to the server as a string, not as a number. So the designers of the language decided that automatic type conversion was the best option. - - This tacit automatic type conversion is indeed convenient. But in practice, this feature causes a lot of errors, which are difficult to find. The code may work or fail, depending on whether you're lucky enough for the automatic conversion to have been done correctly A programmer may not notice this immediately. - - You'll encounter these cases more than once in future tasks. You'll often ask, "Why doesn't my code work the way I expect?". - - Weak typing is a red thread running through all PHP development. - -instructions: | - - Print the result of the expression: `7 - (-8 - -2)`. Try making 7 a string instead of a number. Experiment with other numbers too. - - -# tips: [] diff --git a/modules/27-data-types/50-data-types-weak-typing/description.ru.yml b/modules/27-data-types/50-data-types-weak-typing/description.ru.yml deleted file mode 100644 index abb06317..00000000 --- a/modules/27-data-types/50-data-types-weak-typing/description.ru.yml +++ /dev/null @@ -1,26 +0,0 @@ ---- - -name: Слабая типизация -theory: | - Мы могли складывать числа, потому что операция сложения — это операция для типа «числа». А если применить эту операцию к числу и строке: - - ```php - print_r(1 + '7'); // => 8 - ``` - - `'7'` — это строка, а не число, при этом интерпретатор PHP выдал ответ `8`, как если бы мы складывали два числа. Когда PHP видит несоответствие типов, он сам пытается преобразовать информацию. В данном случае он преобразовал строку `'7'` в число `7`, а потом сложил `1` и `7`. - - Не все языки так делают. PHP — это язык со **слабой типизацией**. Он знает о существовании разных типов, но относится к их использованию не строго. Он пытается преобразовывать информацию, когда это кажется разумным. - - В языках со **строгой типизацией** сложить число со строкой не получится. - - PHP был создан для интернета, а в интернете вся информация — это строки. Даже когда мы вводим на сайте номер телефона или год рождения, на сервер эта информация поступает не как числа, а как строки. Поэтому авторы языка решили, что автоматически преобразовывать типы — правильно и удобно. - - Такое автоматическое неявное преобразование типов с одной стороны и правда удобно. Но на практике это свойство языка создает множество ошибок и проблем, которые трудно найти. Код может иногда работать, а иногда не работать. Это зависит от того, «повезло» ли в конкретном случае с автоматическим преобразованием. Программист это заметит не сразу. - - В дальнейших заданиях мы будем встречаться с таким поведением не раз. Часто будет возникать вопрос «почему мой код работает не так, как я ожидаю?». - -instructions: | - Выведите на экран результат выражения: `7 - (-8 - -2)`. Попробуйте сделать число 7 не числом, а строкой. Поэкспериментируйте с другими числами тоже. - -tips: [] diff --git a/modules/27-data-types/50-data-types-weak-typing/en/data.yml b/modules/27-data-types/50-data-types-weak-typing/en/data.yml index 88298722..b6b82faf 100644 --- a/modules/27-data-types/50-data-types-weak-typing/en/data.yml +++ b/modules/27-data-types/50-data-types-weak-typing/en/data.yml @@ -1 +1,2 @@ +--- name: Weak typing diff --git a/modules/27-data-types/50-data-types-weak-typing/es/data.yml b/modules/27-data-types/50-data-types-weak-typing/es/data.yml index 31b43d9f..301a2d25 100644 --- a/modules/27-data-types/50-data-types-weak-typing/es/data.yml +++ b/modules/27-data-types/50-data-types-weak-typing/es/data.yml @@ -1,2 +1,3 @@ +--- name: Tipado débil tips: [] diff --git a/modules/27-data-types/50-data-types-weak-typing/ru/data.yml b/modules/27-data-types/50-data-types-weak-typing/ru/data.yml index 923d4c50..9253e728 100644 --- a/modules/27-data-types/50-data-types-weak-typing/ru/data.yml +++ b/modules/27-data-types/50-data-types-weak-typing/ru/data.yml @@ -1,2 +1,3 @@ +--- name: Слабая типизация tips: [] diff --git a/modules/27-data-types/55-type-conversion/description.en.yml b/modules/27-data-types/55-type-conversion/description.en.yml deleted file mode 100644 index 5be98839..00000000 --- a/modules/27-data-types/55-type-conversion/description.en.yml +++ /dev/null @@ -1,53 +0,0 @@ ---- - -name: Explicit type conversion -theory: | - - Type conversion is a fairly common operation in web development. On the one hand, you can rely on weak typing to perform it, on the other hand, in many situations it's better to do the conversion explicitly, using special syntax. This code is clearer and more predictable. - - ```php - 5 - ``` - - Type conversion can be used within compound expressions: - - ```php - - Это 5 - - - In more complex situations (when using functions that are passed later) multiple conversions are encountered: `(string) (5 + ((int) '4'))`. The procedure for calculating this expression is as follows: - - ```php - 'Это 5' - ``` - - Явное преобразование типа работает так: перед значением в скобках указывается желаемый тип. В результате значение справа преобразуется в значение другого типа, указанного слева в скобках. На текущий момент мы знакомы только с двумя типами, но преобразование работает для любого типа. - - В более сложных ситуациях при использовании функций, которые будем проходить позже, встречаются множественные преобразования: `(string) (5 + ((int) '4'))`. Порядок вычисления этого выражения следующий: - - ```php - - Father! - Father! - - - Any set of valid characters can be used for a variable name, which includes letters of the English alphabet, numbers, and the `_`. Note that you can't place a digit at the beginning of a name. Variable names are case-sensitive, which means that `hello` and `heLLo` are two different names and thus two distinct variables. Case is important in PHP, never forget it. - - The number of variables you can create isn't limited in any way, large programs contain tens and hundreds of thousands of variable names: - - ```php - Father! - // => Father! - ``` - - В строчке `$greeting = 'Father!'` значение `'Father!'` присваивается переменной с именем `$greeting`. В PHP имена переменных начинаются со знака *$*. В итоге переменная указывает на данные, которые были в нее записаны. - - Когда переменная создана, можно начать ее использовать. - - ## Использование переменной - - Переменная подставляется в те места, где раньше стояло наше слово. Во время выполнения интерпретатор доходит до строчки `print_r($greeting);` и подставляет вместо переменной ее содержимое, а затем выполняет код. - - Для имени переменной используется любой набор допустимых символов, к которым относятся буквы английского алфавита, цифры, знак `_`. При этом цифру нельзя ставить в начале. Имена переменных регистрозависимы, то есть имя `hello` и имя `heLLo` — это два разных имени, значит, это две переменные. Регистр в PHP имеет важное значение, не стоит забывать про него. - - Количество создаваемых переменных не ограничено, большие программы содержат десятки и сотни тысяч имен переменных. Для удобства анализа программы переменные принято создавать как можно ближе к тому месту, где они используются. - -instructions: | - Создайте переменную с именем `$motto` и содержимым `What Is Dead May Never Die!`. Распечатайте содержимое переменной. - -tips: [] - -definitions: - - name: Переменная - description: способ сохранить информацию и дать ей имя для последующего использования в коде. diff --git a/modules/30-variables/10-definition/en/data.yml b/modules/30-variables/10-definition/en/data.yml index cb3aff45..d82844d2 100644 --- a/modules/30-variables/10-definition/en/data.yml +++ b/modules/30-variables/10-definition/en/data.yml @@ -1,3 +1,4 @@ +--- name: What is a variable tips: [] definitions: diff --git a/modules/30-variables/10-definition/es/data.yml b/modules/30-variables/10-definition/es/data.yml index 8d15d493..42b5a697 100644 --- a/modules/30-variables/10-definition/es/data.yml +++ b/modules/30-variables/10-definition/es/data.yml @@ -1,3 +1,4 @@ +--- name: ¿Qué es una variable? tips: [] definitions: diff --git a/modules/30-variables/10-definition/ru/data.yml b/modules/30-variables/10-definition/ru/data.yml index be88755a..1f1965c9 100644 --- a/modules/30-variables/10-definition/ru/data.yml +++ b/modules/30-variables/10-definition/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Что такое переменная tips: [] definitions: diff --git a/modules/30-variables/12-change/description.en.yml b/modules/30-variables/12-change/description.en.yml deleted file mode 100644 index 5753f081..00000000 --- a/modules/30-variables/12-change/description.en.yml +++ /dev/null @@ -1,37 +0,0 @@ ---- - -name: Changing a Variable -theory: | - - The word "variable" itself indicates that it can be changed. Indeed, the value of a variable can change throughout your code. - - ```php - Father! - - $greeting = 'Mother!'; - print_r($greeting); // => Mother! - ``` - - Имя осталось тем же, но внутри другие данные. Переменные в PHP не требуют специального объявления. Вместо этого переменная объявляется при первом ее использовании в программе. - - Никогда нельзя быть точно уверенным, что записано внутри переменной. Чтобы быть спокойным, нужно проанализировать код, который находится перед переменной. Этим занимаются разработчики во время отладки, когда пытаются разобраться, почему программа не работает или работает не так, как задумано. - - Переменные меняются нечасто. Обычно их используют, чтобы хранить. - -instructions: | - В упражнении определена переменная, внутри которой строка. Переопределите значение этой переменной и присвойте ей строку, в которой расположите символы первоначальной строки в обратном порядке. - -tips: - - | - Если в редакторе есть запись `// BEGIN` и `// END`, то код нужно писать между этими строчками. - -definitions: - - name: Переменная - description: способ сохранить информацию и дать ей имя для последующего использования в коде. diff --git a/modules/30-variables/12-change/en/data.yml b/modules/30-variables/12-change/en/data.yml index 3d0fce75..f93ce27e 100644 --- a/modules/30-variables/12-change/en/data.yml +++ b/modules/30-variables/12-change/en/data.yml @@ -1,3 +1,4 @@ +--- name: Changing a Variable tips: - | diff --git a/modules/30-variables/12-change/es/data.yml b/modules/30-variables/12-change/es/data.yml index 99420c3f..62240959 100644 --- a/modules/30-variables/12-change/es/data.yml +++ b/modules/30-variables/12-change/es/data.yml @@ -1,3 +1,4 @@ +--- name: Cambio de variable tips: - > diff --git a/modules/30-variables/12-change/ru/data.yml b/modules/30-variables/12-change/ru/data.yml index 259c4339..f405fc24 100644 --- a/modules/30-variables/12-change/ru/data.yml +++ b/modules/30-variables/12-change/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Изменение переменной tips: - > diff --git a/modules/30-variables/13-variables-naming/description.en.yml b/modules/30-variables/13-variables-naming/description.en.yml deleted file mode 100644 index f8a9edac..00000000 --- a/modules/30-variables/13-variables-naming/description.en.yml +++ /dev/null @@ -1,36 +0,0 @@ ---- - -name: Choosing a variable name -theory: | - - - Let's imagine that the program from the last lesson looks like this: - - ```php - diff --git a/modules/30-variables/13-variables-naming/es/data.yml b/modules/30-variables/13-variables-naming/es/data.yml index ac8a1a74..ddc4e920 100644 --- a/modules/30-variables/13-variables-naming/es/data.yml +++ b/modules/30-variables/13-variables-naming/es/data.yml @@ -1,3 +1,4 @@ +--- name: Elección del nombre de la variable tips: - | diff --git a/modules/30-variables/13-variables-naming/ru/data.yml b/modules/30-variables/13-variables-naming/ru/data.yml index 9e09cf5a..6b30966e 100644 --- a/modules/30-variables/13-variables-naming/ru/data.yml +++ b/modules/30-variables/13-variables-naming/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Выбор имени переменной tips: - > diff --git a/modules/30-variables/14-errors/description.en.yml b/modules/30-variables/14-errors/description.en.yml deleted file mode 100644 index 082e9824..00000000 --- a/modules/30-variables/14-errors/description.en.yml +++ /dev/null @@ -1,31 +0,0 @@ ---- - -name: Errors when handling variables -theory: | - - The main rule is that a variable must be declared before it can be used. If you do it later, the program simply won't work. - - ```php - - Targaryen and Dragon - - -# tips: [] - -# definitions: [] diff --git a/modules/30-variables/14-errors/description.ru.yml b/modules/30-variables/14-errors/description.ru.yml deleted file mode 100644 index fdb0421b..00000000 --- a/modules/30-variables/14-errors/description.ru.yml +++ /dev/null @@ -1,30 +0,0 @@ ---- - -name: Ошибки при работе с переменными -theory: | - Переменную нужно объявить до ее использования. Если сделать это позже, то программа не заработает: - - ```php - - Targaryen and Dragon - - -tips: [] - -definitions: [] diff --git a/modules/30-variables/14-errors/en/data.yml b/modules/30-variables/14-errors/en/data.yml index 62f8085c..98889009 100644 --- a/modules/30-variables/14-errors/en/data.yml +++ b/modules/30-variables/14-errors/en/data.yml @@ -1 +1,2 @@ +--- name: Errors when handling variables diff --git a/modules/30-variables/14-errors/es/data.yml b/modules/30-variables/14-errors/es/data.yml index dc49bc96..daf7214b 100644 --- a/modules/30-variables/14-errors/es/data.yml +++ b/modules/30-variables/14-errors/es/data.yml @@ -1,3 +1,4 @@ +--- name: Errores al trabajar con variables tips: [] definitions: [] diff --git a/modules/30-variables/14-errors/ru/data.yml b/modules/30-variables/14-errors/ru/data.yml index 14e73209..bd74fad5 100644 --- a/modules/30-variables/14-errors/ru/data.yml +++ b/modules/30-variables/14-errors/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Ошибки при работе с переменными tips: [] definitions: [] diff --git a/modules/30-variables/15-expressions/description.en.yml b/modules/30-variables/15-expressions/description.en.yml deleted file mode 100644 index 3c6ea364..00000000 --- a/modules/30-variables/15-expressions/description.en.yml +++ /dev/null @@ -1,97 +0,0 @@ ---- - -name: Expressions in definitions -theory: | - - Variables are helpful not only for storing and reusing data, but also for simplifying complex calculations. Consider an example: you need to convert euros into yuans through dollars. Banks often do this kind of conversion via an intermediate currency when shopping abroad. - - First, convert 50 euros into dollars. Let's assume that one euro equals $1.25: - - ```php - - The price is 431.875 yuans - - - Any variable can be part of any expression. At the moment of calculation, its value is substituted for the variable name. - - The interpreter calculates the value of `$dollarsCount` before this variable is used in other expressions. When it comes time to use a variable, PHP "knows" the value because it's already computed it. - -instructions: | - - Write a program that takes the original number of euros from the `$eurosCount` variable, converts euros to dollars, and displays the value on the screen. Then the program converts the received value into yuans and displays the result on a new line. - - Example output for 100 euros: - - ``` - 125 - 863.75 - ``` - - For the purposes of the exercise, we'll say that: - - 1 euro = $1.25 - - 1 dollar = 6.91 yuans - -tips: - - | - You can use `\n` between the withdrawal of dollars and yuans to go to a new line. diff --git a/modules/30-variables/15-expressions/description.ru.yml b/modules/30-variables/15-expressions/description.ru.yml deleted file mode 100644 index 439cd211..00000000 --- a/modules/30-variables/15-expressions/description.ru.yml +++ /dev/null @@ -1,91 +0,0 @@ ---- - -name: Выражения в определениях -theory: | - Переменные полезны не только для хранения и переиспользования информации. Также они нужны, чтобы упрощать сложные вычисления. В этом уроке мы научимся делать это. - - ## Используем выражение - - Допустим, нам нужно перевести евро в юани через доллары. Подобные конвертации через промежуточную валюту часто делают банки при покупках за рубежом. - - Для начала переведем 50 евро в доллары. Допустим, один евро равен 1.25 доллара: - - ```php - "Kingsroad" - - // Конкатенируем строку и переменную, в которой записана строка - $first = "Kings"; - $what = $first . "road"; - print_r($what); // => "Kingsroad" - - // Конкатенируем две переменные, в которых записаны строки - $last = 'road'; - $what = $first . $last; - print_r($what); // => "Kingsroad" - ``` - -instructions: | - Напишите программу, которая берёт исходное количество евро из переменной `$eurosCount`, переводит евро в доллары и выводит значение на экран. Затем программа полученное значение переводит в юани и выводит результат на новой строчке. - - Пример вывода для 100 евро: - - ``` - 125 - 863.75 - ``` - - Считаем, что: - - 1 евро = 1.25 долларов - - 1 доллар = 6.91 юаней - -tips: - - | - Для перевода строчки можно использовать `\n` между выводом долларов и юаней. diff --git a/modules/30-variables/15-expressions/en/data.yml b/modules/30-variables/15-expressions/en/data.yml index 2e1b8645..7126dcea 100644 --- a/modules/30-variables/15-expressions/en/data.yml +++ b/modules/30-variables/15-expressions/en/data.yml @@ -1,3 +1,4 @@ +--- name: Expressions in definitions tips: - > diff --git a/modules/30-variables/15-expressions/es/data.yml b/modules/30-variables/15-expressions/es/data.yml index 5d569242..5d548a95 100644 --- a/modules/30-variables/15-expressions/es/data.yml +++ b/modules/30-variables/15-expressions/es/data.yml @@ -1,3 +1,4 @@ +--- name: Expresiones en definiciones tips: - > diff --git a/modules/30-variables/15-expressions/ru/data.yml b/modules/30-variables/15-expressions/ru/data.yml index 4a0bb2e1..5de10e09 100644 --- a/modules/30-variables/15-expressions/ru/data.yml +++ b/modules/30-variables/15-expressions/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Выражения в определениях tips: - | diff --git a/modules/30-variables/18-concatenation/description.en.yml b/modules/30-variables/18-concatenation/description.en.yml deleted file mode 100644 index 4f8b3d1d..00000000 --- a/modules/30-variables/18-concatenation/description.en.yml +++ /dev/null @@ -1,62 +0,0 @@ ---- - -name: Variables and concatenation -theory: | - - Let's try concatenating variables so that we can reinforce the previous topic a little. The syntax is still the same, we know how to concatenate (combine) two strings: - - ```php - "Kingsroad" - ``` - - … which means we can concatenate the string and the variable that the string has been written to: - - ```php - "Kingsroad" - ``` - - … and even concatenate two variables with strings in them: - - ```php - "Kingsroad" - ``` - -instructions: | - - Websites are constantly sending emails to their users. One common task is to automatically send a personalized email with the user's name in the header. If you store a person's name as a string somewhere in a website database, the task of generating the header boils down to concatenation. For instance, you have to concatenate the string `Hello` with a string containing their name. - - Write a program that'll create a header and a body of the email using ready-made variables and print the resulting strings. - - For the header, use the `$firstName` and `$greeting` variables for the, and a comma and exclamation point. Print it in the correct order. - - Use the variables `$info` and `$intro` for the body of the email, with the second sentence on a new line. - - The result should look like this: - -
-  Hello, Joffrey!
-  Here is important information about your account security.
-  We couldn't verify you mother's maiden name.
-  
- - Try and do it using just two `print_r()` statements. - -tips: - - | - Consider how you should concatenate the variables (Which string? What order?) to get the two-line output of the email body. - - | - Remember that you can create a string containing only the escape sequence `\n`. diff --git a/modules/30-variables/18-concatenation/description.ru.yml b/modules/30-variables/18-concatenation/description.ru.yml deleted file mode 100644 index 101dbfe1..00000000 --- a/modules/30-variables/18-concatenation/description.ru.yml +++ /dev/null @@ -1,62 +0,0 @@ ---- - -name: Переменные и конкатенация -theory: | - - Для закрепления предыдущей темы попробуем использовать переменные с конкатенацией. Синтаксически ничего не меняется: мы умеем конкатенировать (склеивать) две строки: - - ```php - "Kingsroad" - ``` - - … а значит сумеем конкатенировать строку и одну переменную, в которой записана строка: - - ```php - "Kingsroad" - ``` - - … и даже конкатенировать две переменные, в которых записаны строки: - - ```php - "Kingsroad" - ``` - -instructions: | - - Сайты постоянно посылают письма своим пользователям. Типичная задача — сделать автоматическую отправку персонального письма, где в заголовке будет имя пользователя. Если где-то в базе сайта хранится имя человека в виде строки, то задача генерации заголовка сводится к конкатенации: например, нужно склеить строку `Здравствуйте` со строкой, где записано имя. - - Напишите программу, которая будет генерировать заголовок и тело письма, используя уже готовые переменные, и выводить получившиеся строки на экран. - - Для заголовка используйте переменные `$firstName` и `$greeting`, запятую и восклицательный знак. Выведите это на экран в правильном порядке. - - Для тела письма используйте переменные `$info` и `$intro`, при этом второе предложение должно быть на новой строке. - - Результат на экране будет выглядеть так: - -
-  Hello, Joffrey!
-  Here is important information about your account security.
-  We couldn't verify you mother's maiden name.
-  
- - Выполните задание, используя только два `print_r()`. - -tips: - - | - Подумайте, с какой строкой и в каком порядке нужно склеивать переменные, чтобы получить такой двухстрочный вывод тела письма. - - | - Помните, что можно создать строку, которая содержит только управляющую последовательность `\n`. diff --git a/modules/30-variables/18-concatenation/en/data.yml b/modules/30-variables/18-concatenation/en/data.yml index 4abbe438..a5b81f90 100644 --- a/modules/30-variables/18-concatenation/en/data.yml +++ b/modules/30-variables/18-concatenation/en/data.yml @@ -1,3 +1,4 @@ +--- name: Variables and concatenation tips: - > diff --git a/modules/30-variables/18-concatenation/es/data.yml b/modules/30-variables/18-concatenation/es/data.yml index f702d672..f59a0346 100644 --- a/modules/30-variables/18-concatenation/es/data.yml +++ b/modules/30-variables/18-concatenation/es/data.yml @@ -1,3 +1,4 @@ +--- name: Variables y Concatenación tips: - > diff --git a/modules/30-variables/18-concatenation/ru/data.yml b/modules/30-variables/18-concatenation/ru/data.yml index 5bfc0b79..53c10189 100644 --- a/modules/30-variables/18-concatenation/ru/data.yml +++ b/modules/30-variables/18-concatenation/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Переменные и конкатенация tips: - > diff --git a/modules/30-variables/19-naming-style/description.en.yml b/modules/30-variables/19-naming-style/description.en.yml deleted file mode 100644 index 7c35917c..00000000 --- a/modules/30-variables/19-naming-style/description.en.yml +++ /dev/null @@ -1,33 +0,0 @@ ---- - -name: Variable naming -theory: | - - `$greeting` is an example of a simple name, but not all names are that simple. Often, they're a combination of several words. For example, "user password". Different languages have different naming styles for variables. - - There are three main variable naming conventions, which are sometimes combined. These conventions apply to variable names consisting of several words: - - * kebab-case — a hyphen separates the parts of the name. For example, `my-super-var`. - * snake_case — an underscore is used as a separator. For example, `my_super_var`. - * CamelCase — each word in the name is capitalized. For example, `MySuperVar`. - * lowerCamelCase — each word is capitalized except the first. For example, `mySuperVar`. - - PHP uses CamelCase and its variation lowerCamelCase, where the first letter of the first word is lowercase. We use lowerCamelCase for variables. This means that names are joined together, with all but the first word capitalized: `$userName`. With three words, it looks like this: `$mySuperVariable`. - - Over time, by digging through other people's code, you'll develop the right concepts for naming. - - Names should not only convey meaning, but also correspond to syntactic rules, which aren't usually checked by the language, but are still needed during development. Program writing in today's world is a team effort, and for better teamwork, code should be written in a unified style. Every language has its own rules. PHP has been in chaos for a long time. And the language itself is riddled with contradictions, and not only with names. You will encounter this in the following lessons and in real work. A [coding standard](https://www.php-fig.org/psr/psr-1/), for PHP only appeared relatively recently, and everyone is striving to meet it one way or another. Standards describe multiple aspects. We recommend making a habit of looking at the standard and writing code according to it from the very beginning. - - Fortunately, nowadays, you don't need to remember all the rules from the standard, because there are special programs that check the code automatically and report violations. These programs are called **linters**, and you'll start using them later when you have a little more experience. - -instructions: | - - Create two variables named "first number" and "second number" using lowerCamelCase. Write the number `1.10`, to the first variable and `-100` to the second. Print the product of the numbers written to the resulting variables. - - The code will work with any name, and we only check the printed result, so the task is up to you. - -# tips: [] - -definitions: - - name: A coding standard - description: is a set of syntactic and stylistic rules for writing code. diff --git a/modules/30-variables/19-naming-style/description.ru.yml b/modules/30-variables/19-naming-style/description.ru.yml deleted file mode 100644 index d4c43667..00000000 --- a/modules/30-variables/19-naming-style/description.ru.yml +++ /dev/null @@ -1,33 +0,0 @@ ---- - -name: Именование переменных -theory: | - Некоторые имена довольно просты — например, `$greeting`. Но часто все не так очевидно. Довольно часто имена составные, то есть включают в себя несколько слов. Например, «имя пользователя». В разных языках применяются разные стили кодирования, и имя переменной будет отличаться. - - В именовании переменных можно выделить четыре основных подхода, которые иногда комбинируют друг с другом. Все эти подходы проявляют себя, когда имя переменной состоит из нескольких слов: - - * kebab-case — составные части переменной разделяются дефисом (`my-super-var`) - * snake_case — для разделения используется подчеркивание (`my_super_var`) - * CamelCase — каждое слово в переменной пишется с заглавной буквы (`MySuperVar`) - * lowerCamelCase — каждое слово в переменной пишется с заглавной буквы, кроме первого (`mySuperVar`) - - В PHP используется CamelCase и его вариация lowerCamelCase, при котором первая буква первого слова — строчная. Именно lowerCamelCase применяется для переменных. Это значит, что имена соединяются друг с другом, при этом все имена кроме первого становятся с заглавной буквы: `$userName`. С тремя словами это выглядит так: `$mySuperVariable`. - - Другое общепринятое правило гласит — не используйте транслит для имен, только английский язык. Если вы испытываете сложности с английским, то пользуйтесь переводчиком. Со временем, копаясь в чужом коде, вы сформируете правильные представления об именовании. - - Названия должны не только передавать смысл, но и соответствовать синтаксическим правилам, которые обычно никак не проверяются на уровне языка, но нужны во время разработки. Процесс написания программ в современном мире — коллективная работа, и для лучшего взаимодействия в команде код пишется в едином стиле, как если бы над ним работал один человек. - - В каждом языке свои правила. Относительно недавно в PHP появился общепринятый [стандарт кодирования](https://www.php-fig.org/psr/psr-1/), к которому все так или иначе стремятся. Подобные стандарты описывают множество аспектов. Советуем с самого начала завести привычку заглядывать в стандарт и писать код в соответствие с ним. - - К счастью, сегодня не нужно помнить все правила из стандарта, потому что существуют специальные программы, которые проверяют код автоматически и сообщают о нарушениях. Такие программы называются **линтерами**, и вы начнете их использовать немного позже, когда у вас появится чуть больше опыта. - -instructions: | - Создайте две переменные с именами «первое число» и «второе число» на английском языке, используя lowerCamelCase. Запишите в первую переменную число `1.10`, во вторую — `-100`. Выведите на экран произведение чисел, записанных в получившиеся переменные. - - Код будет работать с любыми названиями, а наша система всегда проверяет только результат на экране, поэтому выполнение этого задания — под вашу ответственность. - -tips: [] - -definitions: - - name: Стандарт кодирования - description: набор синтаксических и стилистических правил написания кода. diff --git a/modules/30-variables/19-naming-style/en/data.yml b/modules/30-variables/19-naming-style/en/data.yml index 69e09706..f58654c7 100644 --- a/modules/30-variables/19-naming-style/en/data.yml +++ b/modules/30-variables/19-naming-style/en/data.yml @@ -1,3 +1,4 @@ +--- name: Variable naming definitions: - name: A coding standard diff --git a/modules/30-variables/19-naming-style/es/data.yml b/modules/30-variables/19-naming-style/es/data.yml index 0fb184c5..1367ff1b 100644 --- a/modules/30-variables/19-naming-style/es/data.yml +++ b/modules/30-variables/19-naming-style/es/data.yml @@ -1,3 +1,4 @@ +--- name: Nomenclatura de variables tips: [] definitions: diff --git a/modules/30-variables/19-naming-style/ru/data.yml b/modules/30-variables/19-naming-style/ru/data.yml index 0a0d6ea9..83df8fc9 100644 --- a/modules/30-variables/19-naming-style/ru/data.yml +++ b/modules/30-variables/19-naming-style/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Именование переменных tips: [] definitions: diff --git a/modules/30-variables/20-magic-numbers/description.en.yml b/modules/30-variables/20-magic-numbers/description.en.yml deleted file mode 100644 index 5ece398c..00000000 --- a/modules/30-variables/20-magic-numbers/description.en.yml +++ /dev/null @@ -1,70 +0,0 @@ ---- - -name: Magic numbers -theory: | - - Let's remember one of the previous lessons: - - ```php - - King Balon the 6th has 102 rooms. - - - Variable names should convey the meaning of numbers, but should remain short and succinct enough to be easily read. - - Note: The code will work with any name, and we only check the printed result, so the task is up to you. - -# tips: [] diff --git a/modules/30-variables/20-magic-numbers/description.ru.yml b/modules/30-variables/20-magic-numbers/description.ru.yml deleted file mode 100644 index 4a0a7483..00000000 --- a/modules/30-variables/20-magic-numbers/description.ru.yml +++ /dev/null @@ -1,70 +0,0 @@ ---- - -name: Магические числа -theory: | - - Вспомним один из прошлых уроков: - - ```php - - King Balon the 6th has 102 rooms. - - - Названия переменных должны передавать смысл чисел, но при этом должны оставаться достаточно короткими и ёмкими для комфортного чтения. - - Помните: код будет работать с любыми названиями, а наша система всегда проверяет только результат на экране, поэтому выполнение этого задания — под вашу ответственность. - -tips: [] diff --git a/modules/30-variables/20-magic-numbers/en/data.yml b/modules/30-variables/20-magic-numbers/en/data.yml index 61f1dc20..0fff2474 100644 --- a/modules/30-variables/20-magic-numbers/en/data.yml +++ b/modules/30-variables/20-magic-numbers/en/data.yml @@ -1 +1,2 @@ +--- name: Magic numbers diff --git a/modules/30-variables/20-magic-numbers/es/data.yml b/modules/30-variables/20-magic-numbers/es/data.yml index a0baa90b..1e3185f3 100644 --- a/modules/30-variables/20-magic-numbers/es/data.yml +++ b/modules/30-variables/20-magic-numbers/es/data.yml @@ -1,2 +1,3 @@ +--- name: Números mágicos tips: [] diff --git a/modules/30-variables/20-magic-numbers/ru/data.yml b/modules/30-variables/20-magic-numbers/ru/data.yml index fded3ed9..a9d34092 100644 --- a/modules/30-variables/20-magic-numbers/ru/data.yml +++ b/modules/30-variables/20-magic-numbers/ru/data.yml @@ -1,2 +1,3 @@ +--- name: Магические числа tips: [] diff --git a/modules/30-variables/23-constants/description.en.yml b/modules/30-variables/23-constants/description.en.yml deleted file mode 100644 index b20a593c..00000000 --- a/modules/30-variables/23-constants/description.en.yml +++ /dev/null @@ -1,35 +0,0 @@ ---- - -name: Constants -theory: | - - Some data, such as mathematical constants, never change. Take the number π. It's always approximately `3.14` and cannot change. - - It's generally accepted in PHP to use constants to refer to this kind of data. - - ```php - 3.14 - ``` - - Creating a constant is different from creating a variable. It starts with the keyword const followed by the constant name. We don't need the dollar sign. Then we assign it the desired value. Constants are usually named with uppercase letters, with `_` as a separator. A constant, like a variable, can be used in any expression. The only limitation is that the constant can't be changed, which sounds pretty logical. - - PHP has a lot of built-in constants that can be used anywhere in the program. Some of them are: - - * `PHP_VERSION` — the current version of PHP - * `PHP_MAXPATHLEN` — maximum file name length - * `PHP_INT_MAX` — the maximum possible value of integers - -instructions: | - - Create a constant, `DRAGONS_BORN_COUNT` and write the number 3 in it. This is the number of dragons born to Daenerys. - -tips: - - | - [List of built-in PHP constants](https://www.php.net/manual/en/reserved.constants.php) - -definitions: - - name: A constant - description: is a way of storing information and naming it for later use in code; constants cannot be changed, unlike variables. diff --git a/modules/30-variables/23-constants/description.ru.yml b/modules/30-variables/23-constants/description.ru.yml deleted file mode 100644 index f35e011b..00000000 --- a/modules/30-variables/23-constants/description.ru.yml +++ /dev/null @@ -1,47 +0,0 @@ ---- - -name: Константы -theory: | - Разработчики часто работают с данными, которые никогда не меняются. Например, число π, которое всегда равно `3.14` и не может измениться. - - Для обращения к подобным данным в PHP принято использовать константы: - - ```php - 3.14 - ``` - - Создание константы отличается от создания переменной. Оно начинается с ключевого слова `const` и последующего имени константы. При этом знак доллара не нужен. Далее ей присваивается нужное значение. - - Константы принято именовать буквами в верхнем регистре с `_` в качестве разделителя. Константа тоже может использоваться в любом выражении. Единственное ограничение — константу нельзя изменить. - - В PHP много встроенных констант, которые можно использовать в любом месте программы. Вот некоторые из них: - - * `PHP_VERSION` — текущая версия PHP - * `PHP_MAXPATHLEN` — максимальная разрешенная длина имени файла - * `PHP_INT_MAX` — максимальное возможное значение целых чисел (integer) - - Кроме обычных констант в PHP существует отдельная группа — **магические константы**. Их отличия заключаются в следующем: - - * Магические константы невозможно определить самому, можно пользоваться только существующими - * Магические константы начинаются и заканчиваются символами `__` (два подчеркивания) - * Магия заключается в том, что такие константы имеют одно и то же значение только в пределах определенной части программы - - Последний пункт говорит о том, что существуют не очень постоянные константы, но их изменения регламентированы и на практике не вызывают проблем. К подобным константам относятся: - - * `__LINE__` — содержит текущую строку файла, в котором она используется - * `__FILE__` — путь до текущего файла - * `__DIR__` — путь до директории, в которой находится текущий файл - -instructions: | - Создайте константу `DRAGONS_BORN_COUNT` и запишите в неё число 3 — это количество драконов, родившихся у Дайенерис. - -tips: - - | - [Список встроенных в PHP констант](https://php.net/manual/ru/reserved.constants.php) - -definitions: - - name: Константа - description: способ сохранить информацию и дать ей имя для последующего использования в коде; константы нельзя изменять, в отличие от переменных. diff --git a/modules/30-variables/23-constants/en/data.yml b/modules/30-variables/23-constants/en/data.yml index e25c101d..7ccf972f 100644 --- a/modules/30-variables/23-constants/en/data.yml +++ b/modules/30-variables/23-constants/en/data.yml @@ -1,3 +1,4 @@ +--- name: Constants tips: - > diff --git a/modules/30-variables/23-constants/es/data.yml b/modules/30-variables/23-constants/es/data.yml index ecaabe5f..55f9c43d 100644 --- a/modules/30-variables/23-constants/es/data.yml +++ b/modules/30-variables/23-constants/es/data.yml @@ -1,3 +1,4 @@ +--- name: Constantes tips: - > diff --git a/modules/30-variables/23-constants/ru/data.yml b/modules/30-variables/23-constants/ru/data.yml index 9465cf76..fb9ffaab 100644 --- a/modules/30-variables/23-constants/ru/data.yml +++ b/modules/30-variables/23-constants/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Константы tips: - > diff --git a/modules/30-variables/24-magic-constants/description.en.yml b/modules/30-variables/24-magic-constants/description.en.yml deleted file mode 100644 index 84e1deac..00000000 --- a/modules/30-variables/24-magic-constants/description.en.yml +++ /dev/null @@ -1,28 +0,0 @@ ---- - -name: Magic constants -theory: | - - In addition to the usual constants, PHP has a separate group of **magic constants**. The differences are as follows: - - * You can't define magic constants yourself, you can only use existing ones. - * Magic constants begin and end with `__` (two underscores). - * The magic is that the constants have the same value only within a certain part of the program. - - This last point may seem strange. What kind of constants are they if their value changes? To put it bluntly, they're not very constant, but their changes are clearly regulated and in practice don't cause problems. Such constants include, for example, the following: - - * `__LINE__` — contains the current line of the file it's used in - * `__FILE__` — path to the current file - * `__DIR__` — the path to the directory where the current file is located - -instructions: | - - Output the path to the current directory using a magic constant. - -tips: - - | - [Magic constants](https://www.php.net/manual/en/language.constants.predefined.php) - -definitions: - - name: A magic constant - description: is a special constant available in PHP; it contains different values in different contexts. diff --git a/modules/30-variables/24-magic-constants/description.ru.yml b/modules/30-variables/24-magic-constants/description.ru.yml deleted file mode 100644 index e9edb01c..00000000 --- a/modules/30-variables/24-magic-constants/description.ru.yml +++ /dev/null @@ -1,28 +0,0 @@ ---- - -name: Магические константы -theory: | - - Кроме обычных констант, в PHP существует отдельная группа — **магические константы**. Их отличия заключаются в следующем: - - * Магические константы невозможно определить самому, можно пользоваться только существующими. - * Магические константы начинаются и заканчиваются символами `__` (два подчёркивания). - * Магия заключается в том, что такие константы имеют одно и то же значение только в пределах определенной части программы. - - Последний пункт может показаться странным. Какие же они константы, если их значение меняется? Прямо скажем, они не очень постоянные, но их изменения четко регламентированы и на практике не вызывают проблем. К подобным константам относятся, например, такие: - - * `__LINE__` — содержит текущую строку файла, в котором она используется - * `__FILE__` — путь до текущего файла - * `__DIR__` — путь до директории, в которой находится текущий файл - -instructions: | - - Выведите на экран путь до текущей директории, используя магическую константу. - -tips: - - | - [Магические константы](https://php.net/manual/ru/language.constants.predefined.php) - -definitions: - - name: Магическая константа - description: специальная константа, доступная в PHP; содержит разное значение в разных контекстах. diff --git a/modules/30-variables/24-magic-constants/en/data.yml b/modules/30-variables/24-magic-constants/en/data.yml index acf077fa..6a4fd466 100644 --- a/modules/30-variables/24-magic-constants/en/data.yml +++ b/modules/30-variables/24-magic-constants/en/data.yml @@ -1,3 +1,4 @@ +--- name: Magic constants tips: - > diff --git a/modules/30-variables/24-magic-constants/es/data.yml b/modules/30-variables/24-magic-constants/es/data.yml index 563d7efa..94a0ad1c 100644 --- a/modules/30-variables/24-magic-constants/es/data.yml +++ b/modules/30-variables/24-magic-constants/es/data.yml @@ -1,3 +1,4 @@ +--- name: Constantes mágicas tips: - > diff --git a/modules/30-variables/24-magic-constants/ru/data.yml b/modules/30-variables/24-magic-constants/ru/data.yml index 99f6d48b..4f55d20c 100644 --- a/modules/30-variables/24-magic-constants/ru/data.yml +++ b/modules/30-variables/24-magic-constants/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Магические константы tips: - > diff --git a/modules/30-variables/25-interpolation/description.en.yml b/modules/30-variables/25-interpolation/description.en.yml deleted file mode 100644 index a1fe43cc..00000000 --- a/modules/30-variables/25-interpolation/description.en.yml +++ /dev/null @@ -1,50 +0,0 @@ ---- - -name: Interpolation -theory: | - - In the lesson on concatenation, we had the task of creating a letter header out of two variables and punctuation marks. You most likely did it this way: - - ```php - Hello, Joffrey! - ``` - - https://replit.com/@hexlet/php-basics-interpolation - - We just created one line and inserted variables into it in the right places using curly brackets (`{}`). It's like we have a blank form where we can enter the desired values. And we no longer have to worry about separate strings for punctuation marks and spaces, all of these characters already exist in our template string. - - You can make as many bracketed blocks as you want on one line. - - **Interpolation only works with double-quoted strings.** - - Nearly all languages favor interpolation over concatenation for combining strings. It glues a string together, and spaces and other characters look good in it. - -instructions: | - - Display the line Do you want to eat, ?`. And the variable `$stark` should be used instead of ``. The output should look like this: - -
-  Do you want to eat, Arya?
-  
- -tips: [] - -definitions: - - name: Interpolation - description: is a way to join strings by inserting variable values into a string template using curly brackets. For example, `\"Hi, {$name}!\"`. diff --git a/modules/30-variables/25-interpolation/description.ru.yml b/modules/30-variables/25-interpolation/description.ru.yml deleted file mode 100644 index 4f968dd9..00000000 --- a/modules/30-variables/25-interpolation/description.ru.yml +++ /dev/null @@ -1,50 +0,0 @@ ---- - -name: Интерполяция -theory: | - Представим, что нам нужно создать заголовок письма из двух переменных и знаков препинания. Эту задачу можно решить так: - - ```php - 'Hello, Joffrey!' - ``` - - Это простой случай, но даже здесь нужно приложить усилия, чтобы увидеть, какая в итоге получится строка. Нужно следить за несколькими кавычками и пробелами, и с первого взгляда сложно понять, что и где начинается и заканчивается. - - Есть другой более удобный способ — **интерполяция**. Так это выглядит: - - ```php - $firstName = 'Joffrey'; - $greeting = 'Hello'; - - // Обратите внимание на ограничители строки — это двойные кавычки - // Интерполяция не работает с одинарными кавычками - print_r("{$greeting}, {$firstName}!"); // => Hello, Joffrey! - ``` - - https://replit.com/@hexlet/php-basics-interpolation - - В этом примере мы создали одну строку и в нужном нам порядке вставили в нее переменные с помощью фигурных скобок (`{}`). Получился шаблон, куда внесены нужные значения. - - Теперь нам не нужно заботиться об отдельных строках для знаков препинания и пробелов. Эти символы записаны в строке-шаблоне. - - В одной строке можно делать сколько угодно блоков с фигурными скобками. Также интерполяция работает только со строками в двойных кавычках. - - Почти во всех языках интерполяция предпочтительнее конкатенации для объединения строк. Строка при этом получается склеенная, и внутри нее хорошо просматриваются пробелы и другие символы. - -instructions: | - Выведите на экран строку `Do you want to eat, ?`. Где вместо `` должна использоваться переменная `$stark`. Вывод должен получиться таким: - -
-  Do you want to eat, Arya?
-  
- -tips: [] - -definitions: - - name: Интерполяция - description: способ соединения строк через вставку значений переменных в строку-шаблон с помощью фигурных скобок. Например, `\"Hi, {$name}!\"`. diff --git a/modules/30-variables/25-interpolation/en/data.yml b/modules/30-variables/25-interpolation/en/data.yml index 4906649b..bc2ba40e 100644 --- a/modules/30-variables/25-interpolation/en/data.yml +++ b/modules/30-variables/25-interpolation/en/data.yml @@ -1,3 +1,4 @@ +--- name: Interpolation tips: [] definitions: diff --git a/modules/30-variables/25-interpolation/es/data.yml b/modules/30-variables/25-interpolation/es/data.yml index 9d2a1a62..8292d7aa 100644 --- a/modules/30-variables/25-interpolation/es/data.yml +++ b/modules/30-variables/25-interpolation/es/data.yml @@ -1,3 +1,4 @@ +--- name: Interpolación tips: [] definitions: diff --git a/modules/30-variables/25-interpolation/ru/data.yml b/modules/30-variables/25-interpolation/ru/data.yml index 686c753f..390eab8f 100644 --- a/modules/30-variables/25-interpolation/ru/data.yml +++ b/modules/30-variables/25-interpolation/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Интерполяция tips: [] definitions: diff --git a/modules/30-variables/30-symbols/description.en.yml b/modules/30-variables/30-symbols/description.en.yml deleted file mode 100644 index 1431e509..00000000 --- a/modules/30-variables/30-symbols/description.en.yml +++ /dev/null @@ -1,64 +0,0 @@ ---- - -name: Extracting characters from string -theory: | - - Sometimes, you need to get a single character from a string. For example, if a website knows the user's first name and surname, and at some point, it needs to output it as`J. Smith`, you need to take the initial letter from the first name. - - ```php - A - ``` - - Square brackets with a number are a special string extraction operator. This number is called an **index** — the position of the character inside the string. Indexes start with 0 in almost all programming languages, so to get the first character, you must specify index `0`. The index of the last element is equal to the length of the string minus one: - - ```php - r - - // Self-check. What will this code print? - $magic = '\nyou'; - print_r($magic[1]); // => ? - ``` - - You're allowed to use negative indices. In this case there's a reference to characters starting from the end of the string. `-1` is the index of the last character, `-2` of the penultimate, and so on. Unlike direct indexing, reverse indexing counts down from `-1`: - - ```php - r - ``` - - You can use variables as well as numbers as an index. Here's an example that will have the same result of displaying the character `A`, but the index inside the square brackets is written as a variable instead of a number: - - ```php - A - ``` - -instructions: | - - You've been given three variables with the names of different people. Put together and print a word out from the characters in this order: - - 1. The third character from the first line. - 2. The second character from the second line. - 3. The fourth character from the third line. - 4. The fifth character from the second line. - 5. The third character from the second line. - - Try using interpolation: you can put individual characters (called via square brackets), as well as variables, inside curly brackets. - -# tips: [] diff --git a/modules/30-variables/30-symbols/description.ru.yml b/modules/30-variables/30-symbols/description.ru.yml deleted file mode 100644 index 09adc433..00000000 --- a/modules/30-variables/30-symbols/description.ru.yml +++ /dev/null @@ -1,66 +0,0 @@ ---- - -name: Извлечение символов из строки -theory: | - В этом уроке мы научимся получать из строки конкретный символ. Например, если сайт знает имя и фамилию пользователя, и в какой-то момент требуется вывести эту информацию в формате `A. Ivanov`. В этом случае нужно взять первый символ из имени: - - ```php - A - ``` - - Квадратные скобки с цифрой — это специальный оператор извлечения строки. Эта цифра называется **индексом** — позицией символа внутри строки. - - Индексы начинаются с нуля почти во всех языках программирования. Чтобы получить первый символ, нужно указать индекс `0`. Индекс последнего элемента равен длине строки минус единица: - - ```php - r - - // Вопрос на самопроверку. Что выведет этот код? - $magic = '\nyou'; - print_r($magic[1]); // => ? - ``` - - Также допустимо использовать отрицательные индексы. В этом случае идет обращение к символам с конца строки. `-1` — индекс последнего символа, `-2` — предпоследнего и так далее. В отличие от прямой индексации обратный отсчет идет от `-1`: - - ```php - r - ``` - - Индексом может быть не только конкретное число, но и значение переменной. Вот пример, который приведет к тому же результату — выводу на экран символа `A`: - - ```php - A - ``` - - Здесь индекс внутри квадратных скобок записан не числом, а переменной. - -instructions: | - Вам даны три переменные с фамилиями разных людей. Составьте и выведите на экран слово из символов в таком порядке: - - 1. Третий символ из первой строки. - 2. Второй символ из второй строки. - 3. Четвертый символ из третьей строки. - 4. Пятый символ из второй строки. - 5. Третий символ из второй строки. - - Попробуйте использовать интерполяцию: внутри фигурных скобок можно помещать не только целые переменные, но и отдельные символы с помощью квадратных скобок. - -tips: [] diff --git a/modules/30-variables/30-symbols/en/data.yml b/modules/30-variables/30-symbols/en/data.yml index 29389f54..e48c7d63 100644 --- a/modules/30-variables/30-symbols/en/data.yml +++ b/modules/30-variables/30-symbols/en/data.yml @@ -1 +1,2 @@ +--- name: Extracting characters from string diff --git a/modules/30-variables/30-symbols/es/data.yml b/modules/30-variables/30-symbols/es/data.yml index c9c9224b..0b60606a 100644 --- a/modules/30-variables/30-symbols/es/data.yml +++ b/modules/30-variables/30-symbols/es/data.yml @@ -1,2 +1,3 @@ +--- name: Extracción de caracteres de una cadena tips: [] diff --git a/modules/30-variables/30-symbols/ru/data.yml b/modules/30-variables/30-symbols/ru/data.yml index 2d07240e..405090b7 100644 --- a/modules/30-variables/30-symbols/ru/data.yml +++ b/modules/30-variables/30-symbols/ru/data.yml @@ -1,2 +1,3 @@ +--- name: Извлечение символов из строки tips: [] diff --git a/modules/30-variables/35-heredoc/description.en.yml b/modules/30-variables/35-heredoc/description.en.yml deleted file mode 100644 index 7e1fbd85..00000000 --- a/modules/30-variables/35-heredoc/description.en.yml +++ /dev/null @@ -1,40 +0,0 @@ ---- - -name: Heredoc -theory: | - - You can use a special syntax called heredoc to define strings in PHP. After the `<<<` operator, you need to specify an identifier with whatever name you like then a line feed, followed by the string itself. The same identifier is added at the end, closing the insertion. This method is convenient for specifying long strings, containing both line feeds and multi-type quotes. - - ```php - - Example of a string, - covering several lines, - using heredoc syntax. - Here we don't need to escape either single ', or double " quotes. - - - Note that the trailing identifier (in this case `EOT`) must not have spaces, otherwise PHP will tell you off for having a syntax error. - -instructions: | - - Write the text below to the `$str` variable. Use heredoc syntax. - - Lannister, Targaryen, Baratheon, Stark, Tyrell... they're all just spokes on a wheel. - This one's on top, then that one's on top, and on and on it spins, crushing those on the ground. - -definitions: [] - -tips: - - | - [Heredoc](https://www.php.net/manual/en/language.types.string.php) diff --git a/modules/30-variables/35-heredoc/description.ru.yml b/modules/30-variables/35-heredoc/description.ru.yml deleted file mode 100644 index 924ce75d..00000000 --- a/modules/30-variables/35-heredoc/description.ru.yml +++ /dev/null @@ -1,36 +0,0 @@ ---- - -name: Heredoc -theory: | - Определять строки в PHP можно с помощью специального heredoc-синтаксиса. После оператора `<<<` необходимо указать идентификатор с произвольным именем, затем перевод строки и саму строку. В конце добавляется тот же идентификатор, который закрывает вставку. Такой способ удобен для задания длинных строк, внутри которых встречаются и переводы строк, и разнотипные кавычки: - - ```php - Пример строки, - // => охватывающей несколько строк, - // => с использованием heredoc-синтаксиса. - // => Здесь не нужно экранировать ни одинарные ', ни двойные " кавычки. - ``` - - Перед закрывающим идентификатором, в нашем случае — `EOT`, не должны стоять пробелы, иначе PHP начнет ругаться на ошибку синтаксиса. - -instructions: | - - Запишите в переменную `$str` текст, который приведен ниже. Используйте heredoc-синтаксис. - - Lannister, Targaryen, Baratheon, Stark, Tyrell... they're all just spokes on a wheel. - This one's on top, then that one's on top, and on and on it spins, crushing those on the ground. - -definitions: [] - -tips: - - | - [Heredoc](https://www.php.net/manual/ru/language.types.string.php#language.types.string.syntax.heredoc) diff --git a/modules/30-variables/35-heredoc/en/data.yml b/modules/30-variables/35-heredoc/en/data.yml index ffebd219..91659b0d 100644 --- a/modules/30-variables/35-heredoc/en/data.yml +++ b/modules/30-variables/35-heredoc/en/data.yml @@ -1,3 +1,4 @@ +--- name: Heredoc definitions: [] tips: diff --git a/modules/30-variables/35-heredoc/es/data.yml b/modules/30-variables/35-heredoc/es/data.yml index a86922a8..7532d897 100644 --- a/modules/30-variables/35-heredoc/es/data.yml +++ b/modules/30-variables/35-heredoc/es/data.yml @@ -1,3 +1,4 @@ +--- name: Heredoc definitions: [] tips: diff --git a/modules/30-variables/35-heredoc/ru/data.yml b/modules/30-variables/35-heredoc/ru/data.yml index 406ecae0..fd50d7c2 100644 --- a/modules/30-variables/35-heredoc/ru/data.yml +++ b/modules/30-variables/35-heredoc/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Heredoc definitions: [] tips: diff --git a/modules/35-calling-functions/100-call/description.en.yml b/modules/35-calling-functions/100-call/description.en.yml deleted file mode 100644 index 8507e2eb..00000000 --- a/modules/35-calling-functions/100-call/description.en.yml +++ /dev/null @@ -1,80 +0,0 @@ ---- - -name: Functions and how they're called -theory: | - - Addition, concatenation, and the other operations discussed are all fairly basic features of programming languages. Mathematics isn't limited to arithmetic, but there are many other areas with their own operations, such as geometry. The same goes for strings: you can flip them, change a letter's case, delete extra characters – and that's just the tip of the iceberg. And finally, at a higher level, there's the applied logic of a particular program. Programs withdraw money, calculate taxes, and generate reports. The number of these jobs is endless and different for each program. And they all have to be somehow expressed in code. - - The notion of a *function* expresses any arbitrary operation in programming. Functions can be both built-in and manually written by a programmer. One built-in function we're already familiar with is `print_r()`. - - Functions are fundamental building blocks in programming, and it's impossible to accomplish anything without them. We need to get acquainted with them as soon as possible because future courses will deal almost exclusively with functions. First, we'll learn how to use the functions we've already defined, and we'll also learn to define our own functions. - - We will start with basic functions that handle strings. Below is an example of a call to `strrev()`, that reverses a string: - - ```php - '!olleH' - ``` - - We created a variable, `$result` and told the interpreter to write the result of the `strrev()` function to it. In this sense, functions are identical to operations; they always return the result of their work. The entry `strrev('Hello!')` means that a function named `strrev` is being called, to which the argument (or parameter) `'Hello!'` has been passed. Arguments are needed for functions to work, just like how operators need operands. The `strrev()` function flips the string passed to it in the arguments. - - Another example is the `strlen()` function, which counts the number of characters in a string - - ```php - 6 - ``` - - The function being called is always indicated by parentheses `()` following the function name. There can be any number of arguments in brackets, and sometimes none at all. The number depends on the function used, for example, the `pow()` function takes two arguments as input and raises the number passed to the power passed in the second parameter. - - ```php - 8 - - // Modern PHP now has a special operator for exponentiation: - $result = 2 ** 3; // 8 - ``` - - And here's an example of a function that takes no arguments. The `rand()` function generates and returns a random number: - - ```php - '!olleH' - ``` - - Мы создали переменную `$result` и указали интерпретатору записать в нее результат, который вернет вызов функции `strrev()`. В этом смысле функции идентичны операциям — они всегда возвращают результат своей работы. - - Запись `strrev('Hello!')` означает, что вызывается функция с именем `strrev`, в которую был передан аргумент или параметр `'Hello!'`. - - Аргументы нужны функциям для работы так же, как операторам нужны операнды. Функция `strrev()` переворачивает ту строку, которая передается ей в аргументах. - - Вызов функции всегда обозначается скобками `()`. Они идут сразу за именем функции. В скобках может быть любое количество аргументов, а иногда — ни одного. Количество зависит от используемой функции. Например, функция `pow()` принимает на вход два аргумента и возводит число, переданное первым параметром, в степень, переданную вторым параметром: - - ```php - 8 - - // В современном PHP появился специальный оператор для возведения в степень - $result = 2 ** 3; // 8 - ``` - - Теперь рассмотрим пример функции, которая не принимает аргументов. Функция `rand()` генерирует и возвращает случайное число: - - ```php - 2 - ``` - - All of this applies for any function, e.g., string functions: - - ```php - 'Last character: p' - ``` - -instructions: | - Print the first and last letters of the sentence stored in the variable `text` using this format: - -
-  First: N
-  Last: t
-  
- - Try to only create one variable you want to assign the text to before you print it. In this lesson, we're practising building a compound expression. - -# tips: [] diff --git a/modules/35-calling-functions/150-calling-functions-expression/description.ru.yml b/modules/35-calling-functions/150-calling-functions-expression/description.ru.yml deleted file mode 100644 index ad8b06b1..00000000 --- a/modules/35-calling-functions/150-calling-functions-expression/description.ru.yml +++ /dev/null @@ -1,74 +0,0 @@ ---- - -name: Вызов функции — выражение -theory: | - В программировании выражение – нечто возвращающее результат, который можно использовать. Напомним, что математические операции по типу сложения и вычитания и строковые операции — это выражения: - - ```php - 2 - ``` - - Все это справедливо для любых функций, например, строковых: - - ```php - Имя пользователя: Toto - ``` - -instructions: | - Выведите на экран первую и последнюю буквы предложения, записанного в переменную `text`, в следующем формате: - -
-  First: N
-  Last: t
-  
- - Постарайтесь создать только одну переменную, в которую сразу запишется нужный текст перед печатью на экран. В этом уроке мы отрабатываем умение собирать составное выражение. - -# tips: [] diff --git a/modules/35-calling-functions/150-calling-functions-expression/en/data.yml b/modules/35-calling-functions/150-calling-functions-expression/en/data.yml index 44c91eb7..2a71902b 100644 --- a/modules/35-calling-functions/150-calling-functions-expression/en/data.yml +++ b/modules/35-calling-functions/150-calling-functions-expression/en/data.yml @@ -1 +1,2 @@ +--- name: Function call - expression diff --git a/modules/35-calling-functions/150-calling-functions-expression/es/data.yml b/modules/35-calling-functions/150-calling-functions-expression/es/data.yml index e4509f9f..c5d60ecf 100644 --- a/modules/35-calling-functions/150-calling-functions-expression/es/data.yml +++ b/modules/35-calling-functions/150-calling-functions-expression/es/data.yml @@ -1 +1,2 @@ +--- name: Llamada a una función - expresión diff --git a/modules/35-calling-functions/150-calling-functions-expression/ru/data.yml b/modules/35-calling-functions/150-calling-functions-expression/ru/data.yml index b61f18a6..d587eabd 100644 --- a/modules/35-calling-functions/150-calling-functions-expression/ru/data.yml +++ b/modules/35-calling-functions/150-calling-functions-expression/ru/data.yml @@ -1 +1,2 @@ +--- name: Вызов функции — выражение diff --git a/modules/35-calling-functions/180-variadic-arguments/description.en.yml b/modules/35-calling-functions/180-variadic-arguments/description.en.yml deleted file mode 100644 index 25a67dfc..00000000 --- a/modules/35-calling-functions/180-variadic-arguments/description.en.yml +++ /dev/null @@ -1,36 +0,0 @@ ---- - -name: Variable Parameter Functions -theory: | - - An interesting feature of some functions is that they can accept a varying number of arguments. We're not talking about default values. Check out this example: - - ```php - diff --git a/modules/35-calling-functions/270-deterministic/ru/data.yml b/modules/35-calling-functions/270-deterministic/ru/data.yml index 21291930..3f4b91c4 100644 --- a/modules/35-calling-functions/270-deterministic/ru/data.yml +++ b/modules/35-calling-functions/270-deterministic/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Детерминированность tips: - > diff --git a/modules/35-calling-functions/900-stdlib/description.en.yml b/modules/35-calling-functions/900-stdlib/description.en.yml deleted file mode 100644 index f75d261f..00000000 --- a/modules/35-calling-functions/900-stdlib/description.en.yml +++ /dev/null @@ -1,30 +0,0 @@ ---- - -name: Standard Library -theory: | - - PHP, like any other language, comes with a set of useful features. Altogether, they make up the so-called **standard library**. It usually contains thousands of functions you can't remember, and that you don't have to. It's assumed that any programmer knows where to look for their documentation and has a rough idea of what they want to achieve. And the rest is a matter of technique. Programming without the Internet is extremely difficult. - - To newcomers, it often looks like this: "Go I know not whither and fetch I know not what". In other words, most people have no idea how to learn about these functions when they don't know anything at all. Oddly enough, there's no way to know everything you need to know once and for all. As you grow as a developer, you'll learn all the exciting features that can solve your problems more elegantly, thus expanding your toolbox. - - Here are some tips to learn about new features: - - * Always keep track of what you're working with at the moment (the data type). You'll almost always find the function you need in the corresponding section of the documentation, e.g. you have to study string functions to work with strings. - * Open the standard functions section of the topic you are studying every now and then and just run through them,, learning the signatures and ways to use them. - * Read other people's code more often, especially code from the libraries you're using. It's all available on GitHub. - - Another feature of PHP functions from the Standard Library is that they're *available globally*. In other words, you can call them anywhere in your program (this doesn't work with functions you've written yourself). Most standard library functions are centered around some functionality or some type of data. For example, there's a large block of functions for processing strings, working with numbers, and so on. We'll go over some of them as you continue to study. - -instructions: | - - The `gettype()` function allows you to determine the type of the argument being passed. The name of the type is returned as a string. For example, a call to `gettype(10)` will return the string `"integer"`. - - Print the type of the value of the variable `$motto`. - -tips: - - | - [Description of string functions](https://www.php.net/manual/en/ref.strings.php) - -definitions: - - name: Standard Library - description: a set of useful features included with the programming language. diff --git a/modules/35-calling-functions/900-stdlib/description.es.yml b/modules/35-calling-functions/900-stdlib/description.es.yml index 3bc400e1..e52fda2c 100644 --- a/modules/35-calling-functions/900-stdlib/description.es.yml +++ b/modules/35-calling-functions/900-stdlib/description.es.yml @@ -5,17 +5,17 @@ theory: | PHP viene con un conjunto de funciones útiles. Juntas, forman la **biblioteca estándar**. Por lo general, incluye miles de funciones que no se pueden aprender todas, ni es necesario hacerlo. En esta lección, daremos recomendaciones sobre cómo trabajar con nuevas funciones. Se supone que cualquier programador sabe dónde buscar la documentación y tiene una idea aproximada de lo que quiere lograr. Por lo tanto, programar sin internet es extremadamente difícil. - + A menudo, los principiantes no saben a dónde ir ni qué buscar. Estos conocimientos y habilidades se adquieren con la experiencia. Durante el aprendizaje y el trabajo, se familiarizan con funciones más interesantes que resuelven sus problemas de una manera más conveniente. Así es como enriquecen su arsenal. - + Aquí hay algunos consejos sobre cómo aprender sobre nuevas funciones: - + * Siempre es necesario tener en cuenta el tipo de datos con el que se está trabajando. Las funciones necesarias se pueden encontrar en la sección correspondiente de la documentación. Por ejemplo, para trabajar con cadenas, es necesario estudiar las funciones de cadenas. * De vez en cuando, es necesario abrir la sección de funciones estándar relacionadas con el tema que se está estudiando. Es necesario estudiarlas, sus firmas y formas de uso. * Es necesario leer el código de otras personas con frecuencia, especialmente el código de bibliotecas que utilizamos. Siempre está disponible en GitHub. - + Otra característica de las funciones de PHP de la biblioteca estándar es que están disponibles globalmente. Se pueden llamar en cualquier parte del programa. Sin embargo, esto no se aplica a las funciones escritas por uno mismo. - + La mayoría de las funciones de la biblioteca estándar se centran en funcionalidades o tipos de datos específicos. Por ejemplo, hay un gran conjunto de funciones para el manejo de cadenas, números, etc. Algunas de ellas las veremos durante el proceso de aprendizaje. instructions: | diff --git a/modules/35-calling-functions/900-stdlib/description.ru.yml b/modules/35-calling-functions/900-stdlib/description.ru.yml deleted file mode 100644 index 04808c5f..00000000 --- a/modules/35-calling-functions/900-stdlib/description.ru.yml +++ /dev/null @@ -1,33 +0,0 @@ ---- - -name: Стандартная библиотека -theory: | - PHP поставляется с набором полезных функций. Вместе они составляют **стандартную библиотеку**. Обычно в нее входят тысячи функций, которые невозможно выучить, что и не нужно делать. В этом уроке мы дадим рекомендации по работе с новыми функциями. - - Подразумевается, что любой программист знает, где искать документацию по ним и примерно представляет себе, чего он хочет достичь. Поэтому программировать без интернета крайне сложно. - - Часто новички не знают, куда нужно идти и что искать. Эти знания и навыки приходят с опытом. Во время обучения и работы они знакомятся с более интересными функциями, которые решают их задачи более удобным способом. Так они и пополняют свой арсенал. - - Вот некоторые советы, как узнавать о новых функциях: - - * Всегда нужно отслеживать, с каким типом данных идет работа. Необходимые функции можно найти в соответствующем разделе документации. Например, для работы со строками нужно изучать строковые функции - * Периодически нужно открывать раздел со стандартными функциями по изучаемой тематике. Нужно изучать их, сигнатуры и способы использования - * Необходимо часто читать чужой код, особенно, код библиотек, которые используются нами. Он всегда доступен на GitHub - - Еще одна особенность функций PHP из стандартной библиотеки в том, что они доступны глобально. Их можно вызывать в любом месте программы. Правда это не работает с функциями, написанными самостоятельно. - - Большинство функций стандартной библиотеки сосредоточено вокруг определенных функциональности или типа данных. Например, есть большой блок функций по обработке строк, с числами и так далее. По некоторым из них мы пройдемся в процессе обучения. - -instructions: | - - Функция `gettype()` позволяет определить тип передаваемого аргумента. Название типа возвращается в виде строки. Например, вызов `gettype(10)` вернёт строку `"integer"` (integer — целое число). - - Выведите на экран тип значения переменной `$motto`. - -tips: - - | - [Описание строковых функций](https://www.php.net/manual/ru/ref.strings.php) - -definitions: - - name: Стандартная библиотека - description: набор полезных функций, входящий в комплект поставки языка программирования. diff --git a/modules/35-calling-functions/900-stdlib/en/data.yml b/modules/35-calling-functions/900-stdlib/en/data.yml index 0728a2c8..c10fba7c 100644 --- a/modules/35-calling-functions/900-stdlib/en/data.yml +++ b/modules/35-calling-functions/900-stdlib/en/data.yml @@ -1,3 +1,4 @@ +--- name: Standard Library tips: - > diff --git a/modules/35-calling-functions/900-stdlib/es/data.yml b/modules/35-calling-functions/900-stdlib/es/data.yml index 5e326774..339745b2 100644 --- a/modules/35-calling-functions/900-stdlib/es/data.yml +++ b/modules/35-calling-functions/900-stdlib/es/data.yml @@ -1,3 +1,4 @@ +--- name: Biblioteca estándar tips: - > diff --git a/modules/35-calling-functions/900-stdlib/ru/data.yml b/modules/35-calling-functions/900-stdlib/ru/data.yml index 95e04b15..4a714081 100644 --- a/modules/35-calling-functions/900-stdlib/ru/data.yml +++ b/modules/35-calling-functions/900-stdlib/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Стандартная библиотека tips: - | diff --git a/modules/40-define-functions/100-define/description.en.yml b/modules/40-define-functions/100-define/description.en.yml deleted file mode 100644 index f83e6cef..00000000 --- a/modules/40-define-functions/100-define/description.en.yml +++ /dev/null @@ -1,78 +0,0 @@ ---- - -name: Creating (defining) functions -theory: | - Defining your own functions makes it much easier to write and maintain programs. Functions allow you to combine several complex operations into one. For example, sending an email on a website is a complex process that involves interacting with external systems over the Internet. Since you can define functions, you can hide all the complexity behind one simple function: - - ```php - Hello, Hexlet! - - ```php - 'Hello, Hexlet!' - ``` - - Unlike normal data, functions perform actions, so their names almost always have to be verbs: "build something", "draw something", "open something", etc. - - Anything described below the indented function name is called the body of the function. It can contain any code. Consider it a small independent program, a set of whatever statements are needed. The body is executed when the function is called. And each function call executes the body independently of other calls. - - The body of the function can be empty: - - ```php - "Winter is coming" - ``` - - In tasks where you have to implement a function, you don't need to call it. Automated tests will call this function to check if it works. The example call above is shown just to give you an idea of how your function will be used. - -tips: - - | - [Naming in programming](https://hexlet.io/blog/posts/code-complete-naming-in-programming) diff --git a/modules/40-define-functions/100-define/description.ru.yml b/modules/40-define-functions/100-define/description.ru.yml deleted file mode 100644 index e64b3528..00000000 --- a/modules/40-define-functions/100-define/description.ru.yml +++ /dev/null @@ -1,87 +0,0 @@ ---- - -name: Создание (определение) функций -theory: | - Напомним, что функции бывают встроенными и добавленными программистом. С первыми мы уже познакомились. А в этом уроке научимся создавать собственные. - - Определение собственных функций значительно упрощает написание и поддержку программ. Функции позволяют объединять сложные операции в одну. Например, отправка письма на сайте — это достаточно сложный процесс. Он включает в себя взаимодействие с внешними системами. - - Благодаря возможности определять функции, всю сложность можно скрыть за одной простой функцией: - - ```php - 'Hello, Hexlet!' - ``` - - В отличие от обычных данных, функции выполняют действия, поэтому их имена практически всегда должны быть глаголами: «построить что-то», «нарисовать что-то», «открыть что-то». - - Все, что описывается ниже имени функции с отступом, называется телом функции. Внутри тела можно описывать любой код. Можно сказать, что это маленькая самостоятельная программа, набор произвольных инструкций. - - Тело выполняется в тот момент, когда запускается функция. Причем каждый вызов функции запускает тело независимо от других вызовов. - - Тело функции может быть пустым: - - ```php - "Winter is coming" - ``` - - В задачах, в которых нужно реализовать функцию, эту функцию вызывать не нужно. Вызывать функцию будут автоматизированные тесты, которые проверяют его работоспособность. Пример с вызовом выше показан только для того, чтобы вы понимали, как ваша функция будет использоваться. - -tips: - - | - [Именование в программировании](https://ru.hexlet.io/blog/posts/naming-in-programming) diff --git a/modules/40-define-functions/100-define/en/data.yml b/modules/40-define-functions/100-define/en/data.yml index b68d57a4..89ed862c 100644 --- a/modules/40-define-functions/100-define/en/data.yml +++ b/modules/40-define-functions/100-define/en/data.yml @@ -1,3 +1,4 @@ +--- name: Creating (defining) functions tips: - > diff --git a/modules/40-define-functions/100-define/es/data.yml b/modules/40-define-functions/100-define/es/data.yml index 862e6618..9f223b9b 100644 --- a/modules/40-define-functions/100-define/es/data.yml +++ b/modules/40-define-functions/100-define/es/data.yml @@ -1,3 +1,4 @@ +--- name: Creación (definición) de funciones tips: - | diff --git a/modules/40-define-functions/100-define/ru/data.yml b/modules/40-define-functions/100-define/ru/data.yml index 22876b2f..d4032eb1 100644 --- a/modules/40-define-functions/100-define/ru/data.yml +++ b/modules/40-define-functions/100-define/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Создание (определение) функций tips: - > diff --git a/modules/40-define-functions/200-return/description.en.yml b/modules/40-define-functions/200-return/description.en.yml deleted file mode 100644 index 1046f01f..00000000 --- a/modules/40-define-functions/200-return/description.en.yml +++ /dev/null @@ -1,150 +0,0 @@ ---- - -name: Return values -theory: | - The functions we defined in the previous lessons ended up printing some data on the screen: - - ```php - NULL - ``` - - Let's change the `greeting()` function so that it starts returning data instead of printing it. To do this, we need to return instead of printing to the screen - - ``` - 'Hello, Hexlet!' - // And even perform some actions on the result - print_r(strtoupper($message)); // => 'HELLO, HEXLET!' - ``` - - Any code after return isn't executed: - - ```php - ? - ``` - -instructions: | - - Implement a function caleed `sayHurrayThreeTimes()`, which returns the string 'hurray! hurray! hurray!'. - - ```php - $hurray = sayHurrayThreeTimes(); - print_r($hurray); // => 'hurray! hurray! hurray!' - - You don't need to call your function, just define it. - -# tips: [] diff --git a/modules/40-define-functions/200-return/description.ru.yml b/modules/40-define-functions/200-return/description.ru.yml deleted file mode 100644 index 7fd50359..00000000 --- a/modules/40-define-functions/200-return/description.ru.yml +++ /dev/null @@ -1,156 +0,0 @@ ---- - -name: Возврат значений -theory: | - Функции, которые мы определяли в предыдущих уроках, заканчивали свою работу тем, что печатали на экран какие-то данные: - - ```php - NULL - ``` - - Изменим функцию `greeting()` так, чтобы она начала возвращать данные вместо их печати. Для этого нам понадобится выполнить возврат вместо печати на экран: - - ```php - 'Hello, Hexlet!' - // И даже выполнить какие-то действия над результатом - print_r(strtoupper($message)); // => 'HELLO, HEXLET!' - ``` - - Любой код после `return` не выполняется: - - ```php - ? - ``` - -instructions: | - - Реализуйте функцию `sayHurrayThreeTimes()`, которая возвращает строку 'hurray! hurray! hurray!'. - - ```php - $hurray = sayHurrayThreeTimes(); - print_r($hurray); // => 'hurray! hurray! hurray!' - - Вам не нужно вызывать свою функцию, только определить её. - -tips: [] diff --git a/modules/40-define-functions/200-return/en/data.yml b/modules/40-define-functions/200-return/en/data.yml index f7488f6f..99c10e9b 100644 --- a/modules/40-define-functions/200-return/en/data.yml +++ b/modules/40-define-functions/200-return/en/data.yml @@ -1 +1,2 @@ +--- name: Return values diff --git a/modules/40-define-functions/200-return/es/data.yml b/modules/40-define-functions/200-return/es/data.yml index 7d838cdd..af29e446 100644 --- a/modules/40-define-functions/200-return/es/data.yml +++ b/modules/40-define-functions/200-return/es/data.yml @@ -1,2 +1,3 @@ +--- name: Retorno de Valores tips: [] diff --git a/modules/40-define-functions/200-return/ru/data.yml b/modules/40-define-functions/200-return/ru/data.yml index af0ea3fa..b9db59ab 100644 --- a/modules/40-define-functions/200-return/ru/data.yml +++ b/modules/40-define-functions/200-return/ru/data.yml @@ -1,2 +1,3 @@ +--- name: Возврат значений tips: [] diff --git a/modules/40-define-functions/300-parameters/description.en.yml b/modules/40-define-functions/300-parameters/description.en.yml deleted file mode 100644 index 5825932a..00000000 --- a/modules/40-define-functions/300-parameters/description.en.yml +++ /dev/null @@ -1,108 +0,0 @@ ---- - -name: Function Parameters -theory: | - Functions can not only return values, but also accept them as parameters. We've encountered function parameters many times before: - - ```php - 'it w...' - ``` - - This function can be implemented in different ways, we'll tell you just one of them. To do it this way, you need to take a substring from the string passed as the first parameter to the `truncate()` function. Use the [substr()](https://www.php.net/manual/en/function.substr.php) function to do this. Think, based on the assignment, which index should you extract the substring from, and how long should it be? - - ```php - 'it w...' - ``` - - Реализовать эту функцию можно различными способами, подскажем лишь один из них. Для решения этим способом вам понадобится взять подстроку из строки, переданной первым параметром в функцию `truncate()`. Используйте для этого функцию [substr()](https://www.php.net/manual/ru/function.substr.php). Подумайте, исходя из задания, с какого индекса и какой длины вам надо извлечь подстроку? - - ```php - "nothing" - myPrint("Hexlet"); // => "Hexlet" - ``` - - There can be any number of default parameters: - - ```php - "nothing" - myPrint("Hexlet"); // => "Hexlet" - ``` - - Параметров со значениями по умолчанию может быть сколько угодно: - - ```php - 4`. It sounds like a question, "Is 5 greater than 4?" The answer is "yes". In other cases, the answer may be "no" (e.g., for `3 < 1`). - - Comparison operators aren't restricted to numbers. You can put them in almost anything, e.g., strings. Every time we visit a website, it compares the username and password we've entered with those in the database. And they'll let us in if we have them (authentication). - - Programming languages have borrowed all the comparison operators from math virtually unchanged. The only major change concerns the equality and inequality operators. In math, the usual equal sign is `=`, but this is rare in programming. In many languages, the symbol `=` is used to assign values to variables, so you need to use `==` or `===` for comparison. - - List of comparison operations: - - * `<` less than - * `<=` less than or equal to - * `>` more than - * `>=` greater than or equal to - * `===` equal to - * `!==` not equal to - - _A tiny note: for equality and inequality, there's also `==` and `!=`, neither of which we'll use because of the possible risks. We'll discuss it later._ - - A logical operation like `5 > 4` or `$password === $text` is an expression, and its result is a special value, `true` or `false`. This is a new data type for us - bool. It has only these two values. - - ```php - 4; - print_r($result); // => true - print_r('one' !== 'one'); // => false - ``` - - Along with strings and integers and rational numbers, the boolean type is one of the most primitive data types in PHP. - - --- - - Try writing a primitive function that takes a child's age as input and decides whether they are a baby or not. Babies are defined as children under a year old: - - ```php - bool(false) - - Now, perform the check on a child who's six months old: - - ```php - bool(true) - - -instructions: | - - Write an `isPensioner()` function that takes age as a single argument and checks if it's over retirement age For the purposes of this exercise, retirement age is considered to be 60 years or over. - - Call examples: - - ```php - 4` или `3 < 1`. Они есть и в программировании. Допустим, когда мы заходим на сайт, введенные логин и пароль сравниваются с теми, какие есть в базе. Если они есть, нас пускают внутрь — аутентифицируют. В этом уроке разберем операции сравнения. - - Языки программирования адаптировали все математические операции сравнения в неизменном виде, кроме операторов равенства и неравенства. В математике для этого используется обычное равно `=`, но в программировании такое встречается редко. - - Во многих языках символ `=` используется, чтобы присвоить переменным значения. Поэтому в php сравнивают с помощью `==`. - - Список операций сравнения: - - * `<` — меньше - * `<=` — меньше или равно - * `>` — больше - * `>=` — больше или равно - * `==` — равно - * `!=` — не равно - - - Эти операции применяются не только к числам. Например, с помощью оператора равенства можно сравнить строки: `password == text` — это сравнение идентичности строк, которые записаны в разных переменных. - - ## Логический тип - - Логическая операция типа `5 > 4` или `password == text` — это выражение. Его результат — специальное значение `True` («истина») или `False` («ложь»). Это новый для нас тип данных — `bool`: - - ```php - 4; - print_r($result); // => true - print_r('one' !== 'one'); // => false - ``` - - Он содержит всего лишь два этих значения. Наряду со строками (string) и целыми и рациональными числами, булев тип (bool) — это один из примитивных типов данных в PHP. - - ## Предикаты - - Попробуем написать простую функцию, которая принимает на вход возраст ребенка и определяет, младенец ли он. Младенцами считаются дети до года. - - Любая операция — это выражение, поэтому единственной строчкой функции пишем «вернуть то значение, которое получится в результате сравнения `age < 1`». В зависимости от того, какой аргумент пришел, сравнение будет истинным (`True`) или ложным (`False`), а `return` вернет этот результат: - - ```php - bool(false) - var_dump(isInfant(0.5)); // => bool(true) - - ``` - -instructions: | - Напишите функцию `isPensioner()`, которая принимает возраст в качестве единственного аргумента и проверяет, является ли этот возраст пенсионным. Пенсионным считается возраст 60 лет и больше. - - Примеры вызова: - - ```php - bool(false) - - This kind of function is called a predicate. Predicate functions answer a question and always (without exception!) return either `true` or `false`. - - Predicates usually have handy names in every language so that they're easily analyzed. In PHP, predicates usually begin with, but are not limited to, the prefixes `is`, `has` or `can`. Examples: - - * `isInfant()` — «is an infant?» - * `hasChildren()` — «does they have children?» - * `isEmpty()` — «is it empty?» - * `hasErrors()` — «are there any errors?» - - A function can only be considered a predicate **if** it returns a bool. - - --- - - Let's write one more predicate function. It takes a string and checks if it's the word `'Castle'`: - - ```php - bool(false) - - -instructions: | - - Write the function `isMister()` that takes a string and checks if it's the word `'Mister'`. - - ```php - diff --git a/modules/45-logic/15-predicates/es/data.yml b/modules/45-logic/15-predicates/es/data.yml index 98e43ce8..3be2e097 100644 --- a/modules/45-logic/15-predicates/es/data.yml +++ b/modules/45-logic/15-predicates/es/data.yml @@ -1,3 +1,4 @@ +--- name: Predicados tips: - | diff --git a/modules/45-logic/15-predicates/ru/data.yml b/modules/45-logic/15-predicates/ru/data.yml index 11196247..2e1983ed 100644 --- a/modules/45-logic/15-predicates/ru/data.yml +++ b/modules/45-logic/15-predicates/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Предикаты tips: - > diff --git a/modules/45-logic/20-logic-combine-expressions/description.en.yml b/modules/45-logic/20-logic-combine-expressions/description.en.yml deleted file mode 100644 index 0b37d305..00000000 --- a/modules/45-logic/20-logic-combine-expressions/description.en.yml +++ /dev/null @@ -1,113 +0,0 @@ ---- - -name: Combining Operations and Functions -theory: | - - Logical operations are expressions. So, **you can combine them with other expressions**. - - Let's say, for example, we want to check if a number is even. In programming, we do this: - - * check the remainder of a division by 2: - * if the remainder is 0, then the number was even - * if the remainder is not 0, then the number was odd - - The remainder of a division is an elementary but crucial concept in arithmetic and algebra, and even number theory and cryptography. The idea is simple; divide a number into several equal groups, and if anything remains, it's the remainder of the division. - - Split some candies equally among individuals: - - - 7 candies, 2 people: 2 x 3 + **remainder 1**. - So, 7 is not a multiple of 2. - - 21 candies, 3 people: 3 x 7 + **remainder 0**. - So, 21 is a multiple of 3. - - 19 candies, 5 people: 5 x 3 + **remainder 4**. - So, 19 is not a multiple of 5. - - The `%` operator calculates the remainder of a division (not to be confused with division itself): - - - `7 % 2` → `1` - - `21 % 3` → `0` - - `19 % 5` → `4` - - ```php - «Вычислить остаток от деления числа `$number` на 2 и сравнить, равен ли остаток нулю; затем вернуть результат проверки равенства»* - - --- - - *Напомним об извлечении символов из строки с помощью квадратных скобок:* - - ```php - 8 && $length < 20; - } - - isCorrectPassword('qwerty'); // false - isCorrectPassword('qwerty1234'); // true - isCorrectPassword('zxcvbnmasdfghjkqwertyui'); // false - ``` - - `&&` means «AND» (called 'conjunction' in mathematical logic). The whole expression is true only when every operand, all of which are part of the compound expression, is true. In other words, `&&` means «both». This operator's priority is lower than that of comparison operators, so the expression works correctly without parentheses. Another widespread operator alongside `&&` is `||` — «OR» (disjunction). It means "one or the other, or both". Operators can be combined in any number and any sequence, but when `&&` and `||`, appear together, you should label priority with parentheses. - - Below is an example of an advanced function that validates a password: - - ```php - 8 && $length < 20) && hasSpecialChars($password); - } - ``` - - Another example. We want to buy an apartment that meets these conditions: an area of 100 square meters or more on any street OR an area of 80 square meters or more, but on `Main Street`. - - We'll write a function that checks the apartment. It takes two arguments, the area (a number) and the street name (a string): - - ```php - = 100 || ($area >= 80 && $street === 'Main Street'); - } - - var_dump(isGoodApartment(91, 'Queens Street')); // => false - var_dump(isGoodApartment(78, 'Queens Street')); // => false - var_dump(isGoodApartment(70, 'Main Street')); // => false - - var_dump(isGoodApartment(120, 'Queens Street')); // => true - var_dump(isGoodApartment(120, 'Main Street')); // => true - var_dump(isGoodApartment(80, 'Main Street')); // => true - ``` - - The area of mathematics dealing with logical operators is called Boolean algebra. The truth tables are shown below, and they can be used to figure out the result of an operator: - - ## `&&` - - | A | B | A `&&` B | - | ----- | ----- | -------- | - | TRUE | TRUE | **TRUE** | - | TRUE | FALSE | FALSE | - | FALSE | TRUE | FALSE | - | FALSE | FALSE | FALSE | - - A couple of examples: - - ```php - 2 && str_starts_with('wow', 'w'); // true - - // true && false; - 'start' === 'start' && 8 < 3; // false - ``` - - ## OR `||` - - | A | B | A `‖` B | - | ----- | ----- | -------- | - | TRUE | TRUE | **TRUE** | - | TRUE | FALSE | **TRUE** | - | FALSE | TRUE | **TRUE** | - | FALSE | FALSE | FALSE | - - A couple of examples: - - ```php - 2 || str_starts_with('wow', 'w'); // true - - // false || false; - 'start' === 'Start' || 3 < 3; // false - ``` - -instructions: | - - Implement the `isLeapYear()` function, which determines whether the year is leap year or not. A leap year is a multiple of 400 (i.e. divisible without a remainder), or is both a multiple of 4 and not a multiple of 100. As you can see, the definition already contains all the required logic, all we need to do is to put it into code: - - ```php - = x <= 20`, где `x` — это длина конкретного пароля. Но в PHP такой трюк не пройдет. - - Нам придется сделать два отдельных логических выражения и соединить их специальным оператором «И»: - - ```php - = 8 && $length <= 20) && hasSpecialChars($password); - } - - isCorrectPassword('qwerty'); // false - isCorrectPassword('qwerty1234'); // true - isCorrectPassword('zxcvbnmasdfghjkqwertyui'); // false - ``` - - Оператор `&&` означает «И» — в математической логике это называют **конъюнкцией**. Все выражение считается истинным только в том случае, когда истинен каждый операнд — каждое из составных выражений. Иными словами, `&&` означает «и то, и другое». Приоритет этого оператора ниже, чем приоритет операторов сравнения, поэтому выражение отрабатывает правильно без скобок. - - Кроме `&&`, часто используется оператор `||` — «ИЛИ» (**дизъюнкция**). Он означает «или то, или другое, или оба». Операторы можно комбинировать в любом количестве и любой последовательности, но когда одновременно встречаются `&&` и `||`, то приоритет лучше задавать скобками. - - Область математики, в которой изучаются логические операторы, называется булевой алгеброй. Ниже увидите **таблицы истинности** — по ним можно определить, каким будет результат, если применить оператора: - - ### И `&&` - - | A | B | A `&&` B | - | ----- | ----- | -------- | - | TRUE | TRUE | **TRUE** | - | TRUE | FALSE | FALSE | - | FALSE | TRUE | FALSE | - | FALSE | FALSE | FALSE | - - ### ИЛИ `||` - - | A | B | A `‖` B | - | ----- | ----- | -------- | - | TRUE | TRUE | **TRUE** | - | TRUE | FALSE | **TRUE** | - | FALSE | TRUE | **TRUE** | - | FALSE | FALSE | FALSE | - -instructions: | - - Реализуйте функцию `isLeapYear()`, которая определяет, является ли год високосным или нет. Год будет високосным, если он кратен (то есть делится без остатка) 400 или он одновременно кратен 4 и не кратен 100. Как видите, в определении уже заложена вся необходимая логика, осталось только переложить её на код: - - ```php - 1 - - ```php - - - *(an empty string has been printed)* - - Another example: - - ```php - 1 - - What happened here: - - The **OR** operator only works with the *bool* type, but it's also given the numbers `1` and `0`. - - 1. `0` is converted to `false` and `1` is converted to `true`. - 2. The result `false || true` is `true`. - 3. Now `print_r()` gets `true`, but it only works with strings (not *bool*). - 4. `true` is converted to `1`. - 5. And the screen displays `1`. - - --- - - In one of our lessons, we looked at the comparison operators `===` and `!==` and mentioned that PHP also has the operators `==` and `!=`, but we shouldn't use them. The difference lies in type conversion: - - ```php - false - var_dump('' == false); // => true - ``` - - An empty string and `false` are different values, so the `===` operator says "false! they're not equal! - - But the `==` operator converts types, making an empty string and `false` equivalent from its point of view. This conversion is implicit, so avoid the `==` and `!=` operators whenever possible. - - --- - - Remember the negation operator: - - ```php - false - ``` - - When you use double negation `!!` the result value is equal to the initial value: - - ```php - true - ``` - - However, this is where type conversions also take place. Therefore, the result of a double negation will always be a _bool_. This trick is used to change the data type. - - --- - - Different programming languages have different transformation rules. Some languages don't convert types themselves at all. Many features of PHP aren't really the best, but this is the historical legacy of the language. If it were created from scratch today, many of the rules and nuances would probably be quite different. - -instructions: | - - Write an `isFalsy()` function that checks if the passed value is interpreted as false from PHP's point of view. To do this check, you need to compare `false` with the passed value using `==`. - - ```php - 1 - print_r(false); // => (на экран выводится пустая строка) - print_r(0 || 1); // => 1 - ``` - - Оператор **ИЛИ** работает только с типом *bool*, но ему даны числа `1` и `0`: - - 1. `0` преобразуется в `false`, а `1` преобразуется в `true` - 2. Результат `false || true` — это `true` - 3. Теперь `print_r()` получает `true`, но он работает только со строками - 4. `true` преобразуется в `1` - 5. И на экран выводится `1` - - Здесь важно отметить также отличие операторов `===` и `==`. Оно как раз заключается в преобразовании типов. - - Пустая строка и `false` — это разные значения, поэтому оператор `===` говорит «Ложь! Они не равны!». - - Но оператор `==` преобразует типы. С его точки зрения, пустая строка и `false` равны. Это преобразование неявное, поэтому по возможности избегайте операторов `==` и `!=`: - - ```php - false - var_dump('' == false); // => true - ``` - - Вспомним операцию отрицания. При двойном отрицании `!!` итоговое значение равно начальному: - - ```php - false - var_dump(!!$answer); // => true - ``` - - Здесь также дополнительно происходят преобразования типа. Поэтому результатом двойного отрицания всегда будет _bool_. Этим приемом пользуются, чтобы поменять тип данных. - - В разных языках программирования разные правила преобразований. Некоторые языки вообще не преобразовывают типы сами. - -instructions: | - - Напишите функцию `isFalsy()`, которая проверяет, трактуется ли переданное значение как ложное с точки зрения PHP. Для выполнения этой проверки вам понадобится сравнить `false` с переданным значением, используя `==`. - - ```php - normal - print_r("\n"); - print_r(getTypeOfSentence('Hodor?')); // => question - ``` - - We recommend not doing that and always writing **curly brackets**. That way, you can clearly see where the conditional construction body starts and ends. The code becomes clearer and more readable. - -instructions: | - - Implement a function, `guessNumber()`, which takes a number and checks if the number is equal to a given number (let it be 42). If it's equal, the function should return the string `'You win!'`, otherwise, it should return the string `'Try again!'`. - - ```php - 10) { ... }`" diff --git a/modules/48-conditionals/30-if/description.ru.yml b/modules/48-conditionals/30-if/description.ru.yml deleted file mode 100644 index 80ccf3b6..00000000 --- a/modules/48-conditionals/30-if/description.ru.yml +++ /dev/null @@ -1,46 +0,0 @@ ---- - -name: Условная конструкция (if) -theory: | - Задача предиката — получить ответ на вопрос, но обычно этого недостаточно и нужно выполнить определенное действие в зависимости от ответа. - - Напишем функцию, которая определяет тип переданного предложения. Для начала она будет отличать обычные предложения от вопросительных: - - ```php - 10) { ... }`" diff --git a/modules/48-conditionals/30-if/en/data.yml b/modules/48-conditionals/30-if/en/data.yml index 7fa4722b..2ef1f222 100644 --- a/modules/48-conditionals/30-if/en/data.yml +++ b/modules/48-conditionals/30-if/en/data.yml @@ -1,3 +1,4 @@ +--- name: Conditional constructions (if) definitions: - name: A conditional construct diff --git a/modules/48-conditionals/30-if/es/data.yml b/modules/48-conditionals/30-if/es/data.yml index adc55b6e..6d78cf49 100644 --- a/modules/48-conditionals/30-if/es/data.yml +++ b/modules/48-conditionals/30-if/es/data.yml @@ -1,3 +1,4 @@ +--- name: Estructura condicional (if) tips: [] definitions: diff --git a/modules/48-conditionals/30-if/ru/data.yml b/modules/48-conditionals/30-if/ru/data.yml index 0e9fce5c..76a60cae 100644 --- a/modules/48-conditionals/30-if/ru/data.yml +++ b/modules/48-conditionals/30-if/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Условная конструкция (if) tips: [] definitions: diff --git a/modules/48-conditionals/40-if-else/description.en.yml b/modules/48-conditionals/40-if-else/description.en.yml deleted file mode 100644 index bfdaafc1..00000000 --- a/modules/48-conditionals/40-if-else/description.en.yml +++ /dev/null @@ -1,76 +0,0 @@ ---- -name: else -theory: | - - Let's try and modify the function from the previous example so that it returns the whole strings of *Sentence is normal* or *Sentence is question* instead of just the sentence type. - - ```php - = 0) { - return $number; - } - - return -$number; - } - - abs(10); // 10 - abs(-10); // 10 - ``` - - Can we write it more concisely? Something like return `return ОТВЕТ В ЗАВИСИМОСТИ ОТ УСЛОВИЯ`? That would require an expression following return, but if is a statement, not an expression. - - In PHP, there's a construct that works like the*if-else* construct, but is an expression. It's called the ternary operator. - - The ternary operator is the only JavaScript operator that takes three operands: - - ```php - = 0 ? $number : -$number; - } - ``` - - It generally looks like this: ` ? : `. - - Let's rewrite the initial version of `getTypeOfSentence()` in the same way: - - Before: - - ```php - = 0 ? $number : -$number`. diff --git a/modules/48-conditionals/60-ternary-operator/description.ru.yml b/modules/48-conditionals/60-ternary-operator/description.ru.yml deleted file mode 100644 index 04457c18..00000000 --- a/modules/48-conditionals/60-ternary-operator/description.ru.yml +++ /dev/null @@ -1,101 +0,0 @@ ---- - -name: Тернарный оператор -theory: | - Посмотрите на определение функции, которая возвращает модуль переданного числа: - - ```php - = 0) { - return $number; - } - - return -$number; - } - - abs(10); // 10 - abs(-10); // 10 - ``` - - Можно ли записать ее лаконичнее? Что-то вроде `return ОТВЕТ В ЗАВИСИМОСТИ ОТ УСЛОВИЯ`? Для этого справа от `return` должно быть выражение. Но есть проблема: `if` — это инструкция, а не выражение. - - В PHP существует конструкция, которая по своему действию аналогична конструкции *if-else*, но при этом является выражением. Она называется **тернарный оператор**, и именно его мы изучим в этом уроке. - - **Тернарный оператор** — единственный в своем роде оператор, требующий три операнда: - - ```php - = 0 ? $number : -$number; - } - ``` - - Общий паттерн выглядит так: - - ```php - ? : ` - ``` - - ![Тернарный оператор](assets/ternary-operator.png) - - Давайте перепишем начальный вариант `getTypeOfSentence()` аналогично. Посмотрим, как было: - - ```php - = 0 ? $number : -$number`. diff --git a/modules/48-conditionals/60-ternary-operator/en/data.yml b/modules/48-conditionals/60-ternary-operator/en/data.yml index 072d9879..33b886a6 100644 --- a/modules/48-conditionals/60-ternary-operator/en/data.yml +++ b/modules/48-conditionals/60-ternary-operator/en/data.yml @@ -1,3 +1,4 @@ +--- name: Ternary operator definitions: - name: The ternary operator diff --git a/modules/48-conditionals/60-ternary-operator/es/data.yml b/modules/48-conditionals/60-ternary-operator/es/data.yml index 47db795b..95fa4478 100644 --- a/modules/48-conditionals/60-ternary-operator/es/data.yml +++ b/modules/48-conditionals/60-ternary-operator/es/data.yml @@ -1,3 +1,4 @@ +--- name: Operador ternario tips: [] definitions: diff --git a/modules/48-conditionals/60-ternary-operator/ru/data.yml b/modules/48-conditionals/60-ternary-operator/ru/data.yml index d53e419c..45db7df9 100644 --- a/modules/48-conditionals/60-ternary-operator/ru/data.yml +++ b/modules/48-conditionals/60-ternary-operator/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Тернарный оператор tips: [] definitions: diff --git a/modules/48-conditionals/65-switch/description.en.yml b/modules/48-conditionals/65-switch/description.en.yml deleted file mode 100644 index 83765358..00000000 --- a/modules/48-conditionals/65-switch/description.en.yml +++ /dev/null @@ -1,130 +0,0 @@ ---- - -name: Switch construction -theory: | - - Many languages include a **switch** in addition to the conditional *if* construct. This is a specialized version of *if*, designed for certain cases. For example, it makes sense for us to have an *if else* chain for equality checks. For example: - - ```php - 1 - // => 2 - // => 3 - ``` - - This function cannot be implemented with the tools we've already learned to use, because the number of outputs on the screen is not known in advance. But with loops this won't be a problem: - - ```php - - 1 - 2 - 3 - finished! - - - Here we use a `while` loop in the function. It has three elements: - - * The key word here is `while`. It's not a function call, although it resembles it. - * Predicate. A condition given in parentheses after `while`. This condition is computed at each iteration. - * Loop body. Block of code in curly brackets. - - The construction reads like this: "do what's specified in the body of the loop as long as the condition (predicate) `$i <= $lastNumber`». Let's look at how this code works to `printNumbers(3)`: - - ```php - - 4 - 3 - 2 - 1 - finished! - - -tips: - - | - [While loop](https://www.php.net/manual/en/control-structures.while.php) - - -definitions: - - name: The While loop - description: is an instruction to repeat the code as long as a certain condition is met. diff --git a/modules/50-loops/10-while/description.ru.yml b/modules/50-loops/10-while/description.ru.yml deleted file mode 100644 index 33e54169..00000000 --- a/modules/50-loops/10-while/description.ru.yml +++ /dev/null @@ -1,153 +0,0 @@ ---- - -name: Цикл While -theory: | - Программы, которые мы пишем, становятся все сложнее и объемнее. Они все еще очень далеки от реальных программ, где количество строк кода измеряется десятками и сотнями тысяч. Текущая сложность уже способна заставить напрячься людей без опыта. Начиная с этого урока, мы переходим к одной из самых сложных базовых тем в программировании – **циклам**. - - Любые прикладные программы служат прагматичным целям. Они помогают управлять сотрудниками и финансами, развлекают, в конце концов. Несмотря на различия, все эти программы выполняют заложенные в них алгоритмы, которые похожи между собой. Что это такое? **Алгоритм** — это последовательность действий или инструкций, которая приводит нас к некоему ожидаемому результату. Это описание подходит под любую программу, но под алгоритмами обычно понимается что-то более специфичное. - - Представьте себе, что у нас есть книга, и мы хотим найти внутри нее какую-то конкретную фразу. Саму фразу мы помним, но не знаем, на какой она странице. Как найти нужную страницу? Самый простой и долгий способ — последовательно просматривать страницы до тех пор, пока мы не найдем нужную фразу. В худшем случае придется просмотреть все страницы, но результат мы все равно получим. Именно этот процесс и называется **алгоритмом**. Он включает в себя перебор страниц и логические проверки, нашли мы фразу или нет. - - Заранее неизвестно количество страниц, которое придется посмотреть, но сам процесс просмотра повторяется из раза в раз совершенно одинаково. Для выполнения таких повторяющихся действий как раз и нужны **циклы**. Каждый такой повтор называется **итерацией**. - - Допустим, мы хотим написать функцию, которая выводит на экран все числа от единицы до указанного (через аргументы): - - ```php - 1 - // => 2 - // => 3 - ``` - - Эту функцию невозможно реализовать уже изученными средствами, так как количество выводов на экран заранее не известно. А с циклами это не составит никаких проблем: - - ```php - 1 - // => 2 - // => 3 - // => finished! - ``` - - https://replit.com/@hexlet/php-basics-while - - В коде функции использован цикл `while`. Он состоит из трех элементов: - - * Ключевое слово `while` — несмотря на схожесть с вызовом функций, это не вызов функции - * Предикат — условие, которое указывается в скобках после `while` и вычисляется на каждой итерации - * Тело цикла — блок кода в фигурных скобках - - Конструкция читается так: «делать то, что указано в теле цикла, пока истинно условие `$i <= $lastNumber`». - - Разберем работу этого кода для вызова `printNumbers(3)`: - - ```php - - 4 - 3 - 2 - 1 - finished! - - -tips: - - | - [Цикл while](https://www.php.net/manual/ru/control-structures.while.php) - - -definitions: - - name: Цикл While - description: инструкция для повторения кода, пока удовлетворяется какое-либо условие. diff --git a/modules/50-loops/10-while/en/data.yml b/modules/50-loops/10-while/en/data.yml index 1c84c649..bad7ba6c 100644 --- a/modules/50-loops/10-while/en/data.yml +++ b/modules/50-loops/10-while/en/data.yml @@ -1,3 +1,4 @@ +--- name: Цикл While tips: - | diff --git a/modules/50-loops/10-while/es/data.yml b/modules/50-loops/10-while/es/data.yml index 0b1cd468..24845c7c 100644 --- a/modules/50-loops/10-while/es/data.yml +++ b/modules/50-loops/10-while/es/data.yml @@ -1,3 +1,4 @@ +--- name: Ciclo While tips: - | diff --git a/modules/50-loops/10-while/ru/data.yml b/modules/50-loops/10-while/ru/data.yml index 48ccd9e4..5438cf8f 100644 --- a/modules/50-loops/10-while/ru/data.yml +++ b/modules/50-loops/10-while/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Цикл While tips: - | diff --git a/modules/50-loops/20-aggregation-numbers/description.en.yml b/modules/50-loops/20-aggregation-numbers/description.en.yml deleted file mode 100644 index 315ec338..00000000 --- a/modules/50-loops/20-aggregation-numbers/description.en.yml +++ /dev/null @@ -1,100 +0,0 @@ ---- - -name: Data aggregation (Numbers) -theory: | - - One particular type of task that can't be done without loops is data aggregation. These tasks can include searching for the maximum or minimum number in an array, and finding sums and arithmetic means. Their main thing is that the result depends on the whole set of data. To calculate the sum, you need to add all the numbers together, to calculate the maximum you need to compare **all** the numbers. - - Anyone who deals with numbers, such as accountants or marketers, will be familiar with these tasks. They're usually done in a spreadsheet like Microsoft Excel or Google Spreadsheets. - - Let's look at the simplest example: finding the sum of a set of numbers. We'll implement a function that adds numbers in the specified range, including bounds. A range in this case is a series of numbers from a certain beginning to a certain end. For example, the range [1, 10] includes all integers from 1 to 10. - - ```php - 'A' - // => 'r' - // => 'y' - // => 'a' - ``` - - https://replit.com/@hexlet/php-basics-loops-using-printnamebysymbol - - The main thing in this code is to set the right condition in `while`. This can be done in two ways: `$i < strlen($name)` or `$i <= strlen($name) - 1`. Both lead to the same result. - -instructions: | - - Write a function, `printReversedWordBySymbol()`, which takes a word as input and prints it by character, just as in the example we gave, but does it in reverse order. - - ```php - 't' - // => 'e' - // => 'l' - // => 'x' - // => 'e' - // => 'H' - ``` - -# tips: [] diff --git a/modules/50-loops/25-iteration-over-string/description.ru.yml b/modules/50-loops/25-iteration-over-string/description.ru.yml deleted file mode 100644 index 8129c7be..00000000 --- a/modules/50-loops/25-iteration-over-string/description.ru.yml +++ /dev/null @@ -1,58 +0,0 @@ ---- - -name: Обход строк -theory: | - Циклы подходят не только для обработки чисел, но и при работе со строками — и это благодаря возможности получить конкретный символ по его индексу. Ниже пример кода, который распечатывает буквы каждого слова на отдельной строке: - - ```php - 'A' - // => 'r' - // => 'y' - // => 'a' - ``` - - https://replit.com/@hexlet/php-basics-loops-using-printnamebysymbol - - Самое главное в этом коде — поставить правильное условие в `while`. Это можно сделать сразу двумя способами: - - * `$i < strlen($name)` - * `$i <= strlen($name) - 1` - - Оба способа приводят к одному результату. - -instructions: | - - Реализуйте функцию `printReversedWordBySymbol()`, которая печатает переданное слово посимвольно, как в примере из теории, но делает это в обратном порядке. - - ```php - 't' - // => 'e' - // => 'l' - // => 'x' - // => 'e' - // => 'H' - ``` - -tips: [] diff --git a/modules/50-loops/25-iteration-over-string/en/data.yml b/modules/50-loops/25-iteration-over-string/en/data.yml index f4407e1f..128a2fdd 100644 --- a/modules/50-loops/25-iteration-over-string/en/data.yml +++ b/modules/50-loops/25-iteration-over-string/en/data.yml @@ -1 +1,2 @@ +--- name: Traversing strings diff --git a/modules/50-loops/25-iteration-over-string/es/data.yml b/modules/50-loops/25-iteration-over-string/es/data.yml index 54646028..b7da48ee 100644 --- a/modules/50-loops/25-iteration-over-string/es/data.yml +++ b/modules/50-loops/25-iteration-over-string/es/data.yml @@ -1,2 +1,3 @@ +--- name: Recorriendo una cadena de caracteres tips: [] diff --git a/modules/50-loops/25-iteration-over-string/ru/data.yml b/modules/50-loops/25-iteration-over-string/ru/data.yml index b7b08fce..8f2c0f78 100644 --- a/modules/50-loops/25-iteration-over-string/ru/data.yml +++ b/modules/50-loops/25-iteration-over-string/ru/data.yml @@ -1,2 +1,3 @@ +--- name: Обход строк tips: [] diff --git a/modules/50-loops/26-conditions-inside-loops/description.en.yml b/modules/50-loops/26-conditions-inside-loops/description.en.yml deleted file mode 100644 index 7e795fde..00000000 --- a/modules/50-loops/26-conditions-inside-loops/description.en.yml +++ /dev/null @@ -1,60 +0,0 @@ ---- - -name: Conditions inside the loop body -theory: | - - Both the loop body and function body are places where statements are executed. So we can use all the things we've already learned in it, such as conditionals. - - Imagine a function that counts how many times a letter appears in a sentence. Here's how it might work: - - ```php - 6 - echo $x; // => 6 - - echo $x++; // => 6 - echo $x; // => 7 - ``` - - What's going on? - - 1. We've printed `++$x`. It's a prefix increment, so first the value is increased by 1, and then the result is returned and printed. - 2. Since the value has changed, `echo $x` outputs 6. - 3. Now display `$x++`. This is a postfix increment, so first the value was returned and displayed, and then the variable was incremented by 1. - 4. Since the value has changed, `echo $x` outputs 7. - - Increment and decrement can make code very complex. Things get especially scary when increments are inserted inside other operations: `$x = $i++ - 7 + --$h`. It's impossible to understand such code, and writing it should be considered a serious crime. - - For example, in JavaScript, the linter (the program that checks the code) immediately starts to complain when it sees increment and decrement being used. - - Usage guidelines: - - * Never mix operations/functions that don't have side effects with operations/functions that do have side effects within a single expression. - * Use increment and decrement only if there's no difference between the prefix and postfix version. It should be separate from other expressions and on a separate line of code. - -instructions: | - - Increment and decrement are not very important operations in PHP, and you can easily manage without them. The assignment in this lesson is not directly related to this topic, but you can use increment and decrement to get used to them. Otherwise, this exercise is just more practice with loops, strings, and conditions. - - Write a function, `makeItFunny()`, which returns a copy of a string passed to it, where each nth element is uppercase. n also needs to be passed to the function. - - To find each nth element, you will need to find the remainder from division `%`. Think about how you can use it. - - ```php - 6 - echo $x; // => 6 - - echo $x++; // => 6 - echo $x; // => 7 - ``` - - Обсудим, что пошагово происходит в коде: - - 1. Вывели на экран `++$x` — это префиксный инкремент, поэтому сначала значение переменной увеличилось на 1, потом результат вернулся и вывелся на экран - 2. Значение изменилось, поэтому `echo $x` вывел 6 - 3. Теперь выводим на экран `$x++` — это постфиксный инкремент, поэтому сначала значение вернулось и вывелось на экран, а потом переменная увеличилась на 1 - 4. Значение изменилось, поэтому `echo $x` вывел 7 - - Инкремент и декремент могут заметно усложнить код. Особенно сложно все становится, когда мы вставляем инкремент внутрь других операций: `$x = $i++ - 7 + --$h`. - - Понять такой код невозможно, поэтому лучше не использовать такие конструкции. Например, в языке JavaScript при проверке кода линтер сразу начинает ругаться, когда видит использование инкремента и декремента. - - Мы советуем пользоваться этими конструкциями так: - - * В рамках одного выражения никогда не смешивайте функции без побочных эффектов с функциями с побочными эффектами (то же самое касается операций) - * Используйте инкремент и декремент только там, где нет разницы между префиксным и постфиксным вариантом: отдельно от всего, на своей собственной строчке кода - -instructions: | - Инкремент и декремент — не очень важные операции в PHP, и без них всегда можно обойтись. Задание в этом уроке не связано напрямую с этой темой, но вы можете использовать инкремент и декремент, чтобы привыкнуть к ним. В остальном это упражнение — ещё одна тренировка работы с циклами, строками и условиями. - - Напишите функцию `makeItFunny()`, которая принимает на вход строку и возвращает её копию, у которой каждый n-ный элемент переведен в верхний регистр. n – задается на входе в функцию. - - Для определения каждого n-ного элемента понадобится остаток от деления `%`. Подумайте, как его можно использовать. - - ```php - Цикл с индексом `$i` повторяется, пока соблюдается условие `$i < strlen($str)`, и после каждого шага `$i` увеличивается на 1 - - Посмотрим, что находится в круглых скобках: - - 1. Начальное значение счетчика — этот код выполняется ровно один раз перед первой итерацией - 2. Предикат (условие повторения циклов) — выполняется на каждой итерации, как и в `while` - 3. Описание изменения счетчика — этот код выполняется в конце каждой итерации - - В остальном принцип работы точно такой же, как у цикла `while`. - -instructions: | - - Реализуйте функцию `sumOfSeries()`, которая считает сумму [ряда целых чисел](https://ru.wikipedia.org/wiki/Числовой_ряд). Ряд задаётся двумя числами — начальным и конечным. - - Функция принимает два аргумента-числа и возвращает сумму ряда. Например, для аргументов `4` и `7` сумма будет `4 + 5 + 6 + 7 = 22`. - - ```php - 13 - ``` - - https://replit.com/@hexlet/php-basics-strings-deeper-strlen - - Languages are divided into two camps. Some have built support into existing functions, and the switch to UTF-8 had no effect on programming. Among them are Java, Ruby, and JavaScript. But PHP went its own special way. In order to work with multibyte encodings, a separate [extension for working with multibyte strings](https://www.php.net/manual/en/book.mbstring.php), was added to the language, which for the most part adds many functions for working with strings, with the only difference that each function of them has the prefix `mb_` (multibyte). - - ```php - 7 - ``` - - https://replit.com/@hexlet/php-strings-deeper-mbstrlen - - But there's no decent alternative to taking a specific character in the string by index. This task should be performed using `mb_substr()`. - - ```php - Øèðîêàÿ ýëåêòðèôèêàöèÿ þæíûõ ãóáåðíèé äàñò ìîùíûé òîë÷îê ïîäú¸ìó ñåëüñêîãî õîçÿéñòâà - - Возникают они потому, что один и тот же код в разных кодировках соответствует совершенно разным символам, за исключением первых 128. Поэтому текст, использующий английские буквы всегда читался, а в остальном — как повезет. Ситуация усугублялась тем, что даже в рамках одного алфавита создавалось множество разных кодировок, например: Windows-1252, KOI8-R, CP 866, ISO 8859-5. - - В языках программирования на тот момент все функции для работы со строками создавались из расчета, что один символ — это один байт. По крайней мере, это свойство было общим для всех кодировок. - - Разные кодировки стали причиной постоянных проблем при взаимодействии людей и программ. Особенно остро эта проблема проявилась с развитием интернета. Такая ситуация не могла продолжаться бесконечно, и в конце концов был создан стандарт **Юникод** (_Unicode_). - - Сейчас он содержит более 100 тысяч символов и включает в себя все существующие языки, даже мертвые. Стандарт Юникод не является кодировкой и ничего не говорит о том, как должны храниться символы в памяти, он лишь определяет связь между символом и некоторым числом. - - Конкретный способ кодирования Юникода определяется соответствующими кодировками, среди которых есть UTF-8, UTF-16 и некоторые другие. В этих кодировках для хранения одного символа уже недостаточно одного байта, они используют больше. UTF-8 ведет себя хитрее: для символов английского алфавита и некоторых других используется один байт, для других алфавитов — два байта. - - После многих лет популяризации Юникода свершилось чудо, и сейчас подавляющее большинство программного обеспечения использует UTF-8. Этот процесс был болезненный и по-разному отразился на языках программирования. Например, в PHP стандартные функции не поддерживают многобайтовые кодировки: - - ```php - 13 - ``` - - https://replit.com/@hexlet/php-basics-strings-deeper-strlen - - Языки разделились на два лагеря. Одни языки встроили поддержку в уже существующие функции — в итоге переход на UTF-8 никак не отразился на процессе программирования. Среди таких языков есть Java, Ruby, JavaScript. - - А вот PHP пошел своим путем. Для работы с многобайтовыми кодировками в язык добавили отдельное [расширение по работе с многобайтовыми строками](https://php.net/manual/ru/book.mbstring.php). По большей части оно добавляет множество функций для работы со строками, с той лишь разницей, что каждая функция из них имеет префикс `mb_` (_multibyte_): - - ```php - 7 - ``` - - https://replit.com/@hexlet/php-strings-deeper-mbstrlen - - А вот достойной альтернативы взятию конкретного символа в строке по индексу не существует. Такую задачу нужно выполнять с помощью функции `mb_substr()`: - - ```php - 1.234 - setlocale(LC_NUMERIC, 'ru_RU'); - print_r(1.234); // => 1,234 - ``` - - If you pass `0` as second argument instead of the locale: `setlocale(LC_ALL, 0)`, the function will return the currently set locale for the category. - -instructions: | - - Display the current locale for the `LC_CTYPE` category. - -# tips: [] - -# definitions: [] diff --git a/modules/60-deep-into-strings/30-locales/description.ru.yml b/modules/60-deep-into-strings/30-locales/description.ru.yml deleted file mode 100644 index c3b20c89..00000000 --- a/modules/60-deep-into-strings/30-locales/description.ru.yml +++ /dev/null @@ -1,47 +0,0 @@ ---- - -name: Локализация -theory: | - Глобализация проявляется во многих аспектах, в том числе в единой системе мер: время, размеры и расстояния, температуры, даты и многое другое. - - Конечно, есть страны, которые выпадают из общего потока. Например, США — это чуть ли не единственная страна, в которой сохраняется и превалирует [английская система мер](https://ru.wikipedia.org/wiki/Английская_система_мер). США использует мили вместо километров и фунты вместо килограммов. Во многих восточных странах по-другому устроены календари, и где-то сейчас идет четырехтысячный год. Но в целом все унифицировано. - - Несмотря на эту унификацию, в каждой стране есть свои особенности по способу записи, сравнению и другим аспектам. Например, в США принято в датах первым ставить месяц, а вторым — день. В некоторых странах для вывода вещественных чисел используют точку, а в некоторых — запятую: `1,234`. - - Эти особенности необязательно привязаны к целой стране. Внутри одной страны может быть множество дополнительных разделений. Каждый такой набор особенностей называют **локалью**, а процесс адаптации к особенностям конкретной локали — **локализацией**. - - Локализация важна в программном обеспечении. Пользователь всегда ожидает, что любой софт или сайт будет работать предсказуемо. В это понятие включается и локализация. Понятно, что самостоятельное решение этой задачи слишком затратно. К счастью, этого делать не нужно. Локализация обычно встроена в сам язык или в специальные библиотеки. - - В PHP для управления локалью используется функция [setlocale()](https://secure.php.net/manual/ru/function.setlocale.php). Эта функция настраивает локаль глобально. Ее вызов влияет на все последующие функции, опирающиеся на локализацию: - - ```php - setlocale(int $category, string $locales, string ...$rest): string|false - ``` - - Первым параметром эта функция принимает название категории (как константу), к которой нужно применить локаль, передающуюся в параметрах дальше: - - * LC_ALL — все нижеперечисленное - * LC_COLLATE — функции сравнения строк `strcoll()` - * LC_CTYPE — функции преобразования и классификации строк, например, `strtoupper()` - * LC_MONETARY — для функции `localeconv()` - * LC_NUMERIC — задает символ десятичного разделения `localeconv()` - * LC_TIME — форматирование даты и времени функцией `strftime()` - - Изучим на примере, как установленная локаль влияет на отображение данных: - - ```php - 1.234 - setlocale(LC_NUMERIC, 'ru_RU'); - print_r(1.234); // => 1,234 - ``` - - Попробуем вторым аргументом передать `0` вместо локали: `setlocale(LC_ALL, 0)`. В таком случае функция будет возвращать текущую установленную локаль для категории. - -instructions: | - Выведите на экран текущую локаль для категории `LC_CTYPE`. - -tips: [] - -definitions: [] diff --git a/modules/60-deep-into-strings/30-locales/en/data.yml b/modules/60-deep-into-strings/30-locales/en/data.yml index ef247bef..0cd642ab 100644 --- a/modules/60-deep-into-strings/30-locales/en/data.yml +++ b/modules/60-deep-into-strings/30-locales/en/data.yml @@ -1 +1,2 @@ +--- name: Localization diff --git a/modules/60-deep-into-strings/30-locales/es/data.yml b/modules/60-deep-into-strings/30-locales/es/data.yml index 9d85e2d7..c86aff56 100644 --- a/modules/60-deep-into-strings/30-locales/es/data.yml +++ b/modules/60-deep-into-strings/30-locales/es/data.yml @@ -1,3 +1,4 @@ +--- name: Localización tips: [] definitions: [] diff --git a/modules/60-deep-into-strings/30-locales/ru/data.yml b/modules/60-deep-into-strings/30-locales/ru/data.yml index 147287bc..3b921039 100644 --- a/modules/60-deep-into-strings/30-locales/ru/data.yml +++ b/modules/60-deep-into-strings/30-locales/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Локализация tips: [] definitions: [] diff --git a/modules/60-deep-into-strings/40-startwith/description.en.yml b/modules/60-deep-into-strings/40-startwith/description.en.yml deleted file mode 100644 index 768e8e56..00000000 --- a/modules/60-deep-into-strings/40-startwith/description.en.yml +++ /dev/null @@ -1,51 +0,0 @@ ---- - -name: Finding a starting position -theory: | - - One of the more frequent tasks when working with strings is to determine whether one string is a part (substring) of another string. Most programming languages have a built-in function for this very task. In PHP, there's no such function, we imitate it by using [mb_strpos()](https://www.php.net/manual/en/function.mb-strpos.php). This function searches for the position of the first occurrence of one string in another. - - ```php - 00:00:00 UTC 1 января 1970 года (четверг) - - Время с этого момента называют «эрой Unix» (_Unix Epoch_). Unix-время представлено целым числом, которое увеличивается с каждой прошедшей секундой без необходимости вычислений для определения года, месяца, дня, часа или минуты. - - Конкретная дата в формате Unix Time называется **timestamp** — временной штамп. Например, для получения текущего _timestamp_ в PHP используется функция `time()`: - - ```php - diff --git a/modules/70-dates/20-date/es/data.yml b/modules/70-dates/20-date/es/data.yml index adfa54e5..48a8c517 100644 --- a/modules/70-dates/20-date/es/data.yml +++ b/modules/70-dates/20-date/es/data.yml @@ -1,3 +1,4 @@ +--- name: Fecha tips: - > diff --git a/modules/70-dates/20-date/ru/data.yml b/modules/70-dates/20-date/ru/data.yml index 87651099..aa58a949 100644 --- a/modules/70-dates/20-date/ru/data.yml +++ b/modules/70-dates/20-date/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Date tips: - | diff --git a/modules/70-dates/30-mktime/description.en.yml b/modules/70-dates/30-mktime/description.en.yml deleted file mode 100644 index 3e5851a6..00000000 --- a/modules/70-dates/30-mktime/description.en.yml +++ /dev/null @@ -1,32 +0,0 @@ ---- - -name: mktime() -theory: | - - The [mktime()](https://www.php.net/manual/en/function.mktime.php) function generates timestamp from time information: seconds, hours, minutes, and date. - - ``` - int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y") ]]]]]] ) - ``` - - `mktime()` is a multi-word function, each part of the date and time is passed as a separate parameter. - - ```php - diff --git a/modules/70-dates/40-timezone/es/data.yml b/modules/70-dates/40-timezone/es/data.yml index 3782fedf..dd52d632 100644 --- a/modules/70-dates/40-timezone/es/data.yml +++ b/modules/70-dates/40-timezone/es/data.yml @@ -1,3 +1,4 @@ +--- name: Zonas horarias tips: - > diff --git a/modules/70-dates/40-timezone/ru/data.yml b/modules/70-dates/40-timezone/ru/data.yml index 372d176a..a89e0740 100644 --- a/modules/70-dates/40-timezone/ru/data.yml +++ b/modules/70-dates/40-timezone/ru/data.yml @@ -1,3 +1,4 @@ +--- name: Часовые пояса (тайм зоны) tips: - >