Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

PHP manual gems

Name: Anonymous 2010-01-04 0:47

Every now and then, one comes across these mind-blowingly profound comments in the PHP manual. Post your discoveries here!

I'll start with this: (from http://www.php.net/manual/en/function.abs.php#94768)

Here is a simple function to make positives to negative and negatives to positive. This is function:

<?php
function turn($x)
     {
     $y = abs($x);
     if ($y == $x)  
         return "-$y";  
     else      
         return "$y";  
     }
?>


You can use this code:

<?php
echo turn(-5) + turn(10);
?>


The output is:

-5

;
Because 5 + -10 = -10

Name: Anonymous 2010-01-04 18:32

http://www.php.net/manual/en/function.fopen.php#94643

This is a function for reading or writing to a text file...
The function has three modes, READ, WRITE, and READ/WRITE... READ, returns the text of a file, or returns FALSE if the file isn't found. WRITE creates or overrides a file with the text from the $input string, WRITE returns TRUE or FALSE depending on success or failure. READ/WRITE reads a text file, then writes the string from $input to the end of the file, like WRITE, it returns TRUE or FALSE depending on success or failure.


<?php
function openFile($file, $mode, $input) {
    if ($mode == "READ") {
        if (file_exists($file)) {
            $handle = fopen($file, "r");
            $output = fread($handle, filesize($file));
            return $output; // output file text
        } else {
            return false; // failed.
        }
    } elseif ($mode == "WRITE") {
        $handle = fopen($file, "w");
        if (!fwrite($handle, $input)) {
            return false; // failed.
        } else {
            return true; //success.
        }
    } elseif ($mode == "READ/WRITE") {      
        if (file_exists($file) && isset($input)) {
            $handle = fopen($file "r+");
            $read = fread($handle, filesize($file));
            $data = $read.$input;
            if (!fwrite($handle, $data)) {
                return false; // failed.
            } else {
                return true; // success.
            }
        } else {
            return false; // failed.
        }
    } else {
        return false; // failed.
    }
    fclose($handle);
}
?>
EXAMPLE CALLS:
<php
openFile2("files/text.txt", "WRITE", "Hello World!");
echo openFile2("files/text.txt", "READ"); // OUTPUT > Hello World!
openFile2("files/text.txt", "READ/WRITE", "!!");
echo openFile2("files/text.txt", "READ"); // OUTPUT > Hello World!!!
?>

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List