PHP example

plain text

paragraph

"; echo 'Hello Upsorn'; echo 'How are' . ' you?'; print "Hi"; printf("Let's write PHP"); $name = "Duh"; $age = 25; $hourlyRate = 10.50; $hours = 40; echo $name . ' is ' . $age . "years old.
"; echo "$name makes \$ $hourlyRate an hour.
"; echo "$name makes \$ " . number_format($hourlyRate, 2) . " an hour.
"; // single quote -- slightly faster (not parse) // double quote -- interpreter parses to check if there are any variables within the string $paid = $hourlyRate * $hours; echo $paid; echo "
"; // create indexed array $colors = []; $colors[] = "purpose"; // 0 $colors[] = "blue"; // 1 $colors[5] = "green"; // 5, skip indexes $colors[] = 6; $colors[] = true; echo $colors[1] . "
"; var_dump($colors); // include type, size, value echo "
"; // observe what happen with skipped indexes for ($i=0; $i"; // for each item in a collection of colors // "as" allow us to specify a running variable foreach ($colors as $color) echo $color . "
"; // can do sizeof(collection) or count(collecton) // diff developers who created each version of php, results in many version doing the same thing // can do while loop or do-while loop but doesn't have special treatment like foreach echo "
"; // create associative array // sometimes, we want to access data using some meaningful key, not just index 0,1,... // $friends = ["k1" => "v1", "k2" => "v2"]; // keys must be of primitive type, unique (latest overwrite the previous) $friends = array( "name" => "Wacky", "age" => 20, "favorite_color" => "blue", "favorite_food" => "pizza", true => "boolean true", // true become 1 false => "boolean false", // false become 0 true => "replace true" // value of this replace the above true ); echo $friends["name"] . "
"; // single or double quotes, be sure to match var_dump($friends); $friends['age'] = 30; var_dump($friends); // add element to an array $friends['newkey'] = 'something'; var_dump($friends); foreach ($friends as $friend) echo $friend . '
'; // refer to just the value, not give us the key foreach ($friends as $mykey => $friend) echo $mykey . ' --- ' . $friend . '
'; echo "
"; // to remove an element (key-value pair) from an array unset($friends['newkey']); // go to the array, remove the matched key var_dump($friends); echo "
"; // try removing again unset($friends['newkey']); // not found, nothing happen var_dump($friends); echo "
"; $str = 'a,b,c,d,e'; $pieces = explode(',', $str); // split the string based on a particular character var_dump($pieces); echo "
"; $newstr = implode("@", $pieces); // construct/join the item in array with @ var_dump($newstr); // explode and implode will be useful when we know the delimiter, such as csv file // str_replace(find, replace_with, string) $another_str = str_replace("world", "@@@", "Hello world"); echo $another_str . '
'; $another_str = str_replace("world", "@@@", "Hello World"); // case sensitive echo $another_str . '
'; ?>