Creative portal «Terra Ad Caelum»
Book Reader
Books overview

 

Quotes

416

 

Quotation:

Page:        

15 p.

If you’re already a PHP programmer and are primarily interested in what’s new in PHP 7, Upgrading to PHP 7 by Davey Shafik (O’Reilly) is a great place to look for all the details on what’s new and different in this latest version of PHP. Bruno Skvorc’s compilation of links and references at SitePoint also has a lot of great detail.

44 p.

To compare strings without paying attention to case, use strcasecmp(). It compares two strings while ignoring differences in capitalization. If the two strings you provide to strcasecmp() are the same independent of any differences between upper- and lowercase letters, it returns 0.

46 p.

printf("ZIP is %05d and the date is %02d/%02d/%d", $zip, $month, $day, $year);... $min = 40; $max = 40; printf("The computer can operate between %+d and %+d degrees Celsius.", $min, $max); // The computer can operate between -40 and +40 degrees Celsius

49 p.

In addition to the plus sign (+) for addition, the minus sign (-) for subtraction, the forward slash (/) for division, and the asterisk (*) for multiplication, PHP also sup‐ports two asterisks (**) for exponentiation and the percent sign (%) for modulus division (returning the remainder of a division operation)

50 p.

Dividing one integer by another produces a floating-point result if the two integers don’t divide evenly. Similarly, if you do something to an integer that makes it larger than the maximum allowable integer or smaller than the minimum possible integer, the PHP engine converts the result into a floating-point number so you get the proper result for your calculation.

51 p.

Keep in mind that, despite the alluring aesthetic possibilities of variable names with emoticons in them, most PHP code sticks with digits, underscores, and Basic Latin letters.

66 p.

The “dictionary” that the PHP engine uses for comparing strings is the ASCII codes for characters. This puts numerals before letters, and orders the numerals from 0 to 9. It also puts uppercase letters before lowercase letters.

67 p.

the Collator class, which can compare and sort text in different character sets

68 p.

The spaceship operator () does comparison similar to strcmp(), but for any data type. It evaluates to a negative number when its lefthand operand is less than the righthand operand, a positive number when the righthand operand is bigger, and 0 when they are equal.

69 p.

The spaceship operator was introduced in PHP 7. If you’re using an older version of PHP, stick with the other comparison operators

78 p.

The short array syntax was introduced in PHP 5.4. If you’re using an earlier version of PHP, you need to stick with array().

88 p.

The interpolation in Example 4-19 works only with array keys that consist exclusively of letters, numbers, and underscores. If you have an array key that has whitespace or other punctuation in it, interpolate it with curly braces,...

92 p.

The array-sorting functions sort(), asort(), and ksort() have counterparts that sort in descending order. The reverse-sorting functions are named rsort(), arsort(), and krsort(). They work exactly the same as sort(), asort(), and ksort(), except they sort the arrays so the largest (or alphabetically last) key or value is first in the sorted array, and subsequent elements are arranged in descending order.

100 p.

When you’re writing computer programs, laziness is a virtue.

101 p.

The PHP engine doesn’t prevent you from having a variable and a function with the same name, but you should avoid it if you can.

102 p.

Functions can be defined before or after they are called. The PHP engine reads the entire program file and takes care of all the function definitions before it runs any of the commands in the file

115 p.

Type declarations (function input): array (5.1), bool (7.0), callable (5.4), float (7.0), int (7.0), string (7.0).

116 p.

PHP 7 also supports type declarations for the kind of value a function returns. To enforce checking of the return type of a function, put a : after the ) that closes the argument list, and then the return type declaration.

117 p.

Even with type declarations, PHP 7 attempts to convert the type of an argument or return value that doesn’t actually match a type declaration but could match it. Numeric values get silently converted to strings, and strings that contain numbers get silently converted to the appropriate numeric type. You can turn off this loosey-goosey default in a particular file by putting declare(strict_types=1); at the top of the file. Then, the arguments and return values of any function calls in that file must match the type declarations (but you can still pass an integer as an argument declared as float).

141 p.

The value of $_SERVER['REQUEST_METHOD'] is always uppercase, no matter how the value of the action attribute in the tag is written.

144 p.

To avoid a warning message from PHP when no POST variables have been submitted... The null coalesce operator was introduced in PHP 7

153 p.

$input['age'] = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, array('options' => array('min_range' => 18, 'max_range' => 65)))

159 p.

The strip_tags() function is very convenient, but it behaves poorly with mismatched "less" and "more" characters... It starts stripping once it sees that "less"-character and never stops because there’s no corresponding "more"-character.

180 p.

different syntax for automatically assigning unique integer IDs. For example, MySQL uses the AUTO_INCREMENT keyword, PostgreSQL uses serial types, and Oracle uses sequences.... For example, MySQL allows VARCHAR columns to be up to 255 characters long, but Microsoft SQL Server allows VARCHAR columns to be up to 8,000 characters long. Check your database manual for the specifics that apply to you.

188 p.

PDO provides a helpful feature called prepared statements

200 p.

The regular quoting puts a backslash before single quotes, but also before backslashes. If strtr() processes the string first, a submitted value such as %chicken% becomes \%chicken\%

201 p.

$dish = strtr($dish, array('_' => '\_', '%' => '\%'));

212 p.

Although file() is very convenient, it can be problematic with very large files. It reads the whole file to build the array of lines—and with a file that contains lots of lines, that may use up too much memory. In that case, you need to read the file line-by-line... Reading a file one line at a time $fh = fopen('people.txt','rb'); while ((! feof($fh)) && ($line = fgets($fh))

217 p.

To generate more complicated spreadsheets that include formulas, formatting, and images, use the PHPOffice PHPExcel package.

218 p.

Just like talking to a database program, working with files means interacting with resources external to your program. This means you have to worry about all sorts of things that can cause problems, such as operating system file permissions or a disk running out of free space.

228 p.

If you don’t want PHP to monkey with your cookie value, use setrawcookie() instead of setcookie(). However, with setrawcookie(), your cookie value cannot contain =, ,, ;, or any whitespace.

229 p.

The cookie expires at noon on October 1, 2019 $d = new DateTime("2019-10-01 12:00:00"); setcookie('much-longer-userid','ralph', $d->format('U'));

230 p.

The part of the URL after the hostname (such as /buy.php, /catalog/list.php, or /users/ profile.php) is called the path. To tell the web client to match against a different path when determining whether to send a cookie to the server, provide that path as the fourth argument to setcookie().

237 p.

“A 1% chance” sounds awfully unpredictable for a computer program. It is. But that randomness makes things more efficient. On a busy site, searching for expired sessions to destroy at the beginning of every request would consume too much server power. You’re not stuck with that 1% chance if you’d like expired sessions to be removed more promptly.

251 p.

Did you know that = file_get_contents('http://numbersapi.com/09/27') ?> The Numbers API knows a lot of facts about each day, but for me the result of Example 11-1 looked like this: Did you know that September 27th is the day in 1961 that Sierra Leone joins the United Nations.... http_build_query() function is useful when you need to build an API URL that includes query string parameters... The NDB API used for examples in this chapter requires that requests have a parameter named api_key whose value is a distinct API key that you get by signing up for the API. To get your own API key, visit https://api.data.gov/signup/. It’s free, quick, and requires you to provide minimal information—just your name and email address.... $params = array('api_key' => NDB_API_KEY, 'q' => 'black pepper', 'format' => 'json'); $url =... arams = array('api_key' => NDB_API_KEY, 'q' => 'black pepper', 'format' => 'json'); $url = "http://api.nal.usda.gov/ndb/search?" . http_build_query($params);

253 p.

stream_context_create() function. Different kinds of streams support different kinds of options for their contexts. For the http stream, a header option gets a string value containing the names and values of any headers to send with the HTTP request.

291 p.

The assertSame() assertion is similar to assertEquals() but goes one step further. In addition to testing that two values are equal, it also tests that the types of the two values are the same. The assertEquals() assertion passes if given the string '130' and the integer 130, but assertSame() fails

294 p.

But as your project accumulates more and more functionality (and perhaps more and more people working on it), the accumulated tests are invaluable

307 p.

// DateTime understands microseconds $f = new DateTime('2015-03-10 17:34:45.326425'); // Epoch timestamp must be prefixed with @ $g = new DateTime('@381718923');

312 p.

If you’ve used a package manager in another language (such as npm with JavaScript, gem with Ruby, or cpan with Perl) you’ll find the Composer experience familiar and pleasant.

331 p.

// Zip code to look up weather for $zip = "98052"; // YQL query to find the weather // See https://developer.yahoo.com/weather/ for more info $yql = 'select item.condition from weather.forecast where woeid in '. '(select woeid from geo.places(1) where text="'.$zip.'")'; // The params that the Yahoo! YQL query endpoint expects $params = array("q" => $yql, "format" => "json", "env" => "store://datatables.org/alltableswithkeys");

333 p.

PHP REPL. Run php -a and you get a php > prompt at which you can type in some PHP code and immediately see the results

334 p.

There are other REPLs aside from the built-in one. A nifty example is PsySH. You can install it with Composer: php composer.phar global require psy/psysh. That global before require tells Composer to install PsySH not in any packagespecific directory but in a systemwide Composer directory.

337 p.

Manipulating Text Since the strlen() function only counts bytes, it reports incorrect results when a character requires more than one byte. To count the characters in a string, independent of how many bytes each character requires, use mb_strlen()

339 p.

Because strtoupper() and strtolower() work on individual bytes, they don’t replace whole multibyte characters with the correct equivalents like mb_strtoupper() and mb_strtolower() do.... PHP’s built-in text sorting and comparison functions also operate on a byte-by-byte basis following the order of letters in the English alphabet. Turn to the Collator class to do these operations in a character-aware manner.

340 p.

The MessageFormatter class helps you generate messages that are appropriately localized for different places.

341 p.

Formatting numbers in a message $msg = "The cost is {0,number,currency}."; $fmtUS = new MessageFormatter('en_US', $msg); $fmtGB = new MessageFormatter('en_GB', $msg); print $fmtUS->format(array(4.21)) . "\n"; print $fmtGB->format(array(4.21)) . "\n"; Example 20-7 prints: The cost is $4.21. The cost is £4.21.... MessageFormatter relies on the powerful ICU library, it uses its internal database of currency symbols, number formatting, and other rules about how different places and languages organize information to produce proper output.... ICU User Guide to Formatting and Parsing

347 p.

If your web server talks to the PHP engine using CGI or FastCGI, you can also set configuration directives in .user.ini files. In PHP 5.3.0 and later, the PHP engine looks for a file called .user.ini in the same directory as the PHP program it’s running.