Skip to main content

Posts

Showing posts from January, 2020

PHP Arrays

An array stores multiple values in one single variable: Example <?php $cars =  array ( "Volvo" ,  "BMW" ,  "Toyota" ); echo   "I like "  . $cars[ 0 ] .  ", "  . $cars[ 1 ] .  " and "  . $cars[ 2 ] .  "." ; ?> What is an Array? An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: $cars1 = "Volvo"; $cars2 = "BMW"; $cars3 = "Toyota"; However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is to create an array! An array can hold many values under a single name, and you can access the values by referring to an index number. Create an Array in PHP In PHP, the  array()  function is used to create an array: array(); Get The Length of an Array - The count() Function The  ...

PHP Functions

Create a User Defined Function in PHP A user-defined function declaration starts with the word  function : Syntax function  functionName () {     code to be executed ; } Tip:  Give the function a name that reflects what the function does! In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call the function, just write its name followed by brackets (): Example <?php function  writeMsg() {      echo   "Hello world!" ; } writeMsg();  // call the function ?> PHP Function Arguments Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The followin...

PHP Loops

PHP  while  Loop The  while  loop - Loops through a block of code as long as the specified condition is true. The PHP while Loop The  while  loop executes a block of code as long as the specified condition is true. Syntax while ( condition is true ) {     code to be executed ; } Example <?php $x =  1 ; while ($x <=  5 ) {      echo   "The number is: $x <br>" ;     $x++; } ?> Example Explained $x = 1; - Initialize the loop counter ($x), and set the start value to 1 $x <= 5 - Continue the loop as long as $x is less than or equal to 5 $x++; - Increase the loop counter value by 1 for each iteration This example counts to 100 by tens: Example <?php $x =  0 ; while ($x <=  100 ) {      echo   "The number is: $x <br>" ;     $x+= 10 ; } ?> PHP  do while  Loop The  do...while  loop - Loops through a b...