Skip to content

Instantly share code, notes, and snippets.

@phpnode
Created June 4, 2011 13:09
Show Gist options
  • Save phpnode/1007892 to your computer and use it in GitHub Desktop.
Save phpnode/1007892 to your computer and use it in GitHub Desktop.
<?php
// Multiply each item in a list by 2
print_r(array_map(function($a) { return $a * 2; }, range(1,1000)));
// Sum a list of numbers
print_r(array_sum(range(1,1000))."\n");
// Verify if word exists in string
$wordList = array("register globals","magic quotes");
$text = "one of my favorite PHP features is magic quotes";
array_walk($wordList,function ($v) use (&$contains, $text) { if (!$contains) { $contains = (bool) strstr($text, $v); }}, $contains);
if ($contains) {
echo "a match!...\n";
}
// Read in a File
$lines = file("/path/to/filename");
// Happy Birthday
array_walk(range(1,4), function ($i) { echo "Happy Birthday ".($i == 3 ? "dear NAME" : "to You")."\n"; });
// Filter list of numbers
$results = array(49, 58, 76, 82, 88, 90);
array_walk($results, function ($v) use (&$passed, &$failed) { if ($v > 60) { $passed[] = $v; } else { $failed[] = $v; } });
print_r($passed);
print_r($failed);
// Fetch and Parse a XML web service
$results = simplexml_load_file("http://search.twitter.com/search.atom?&q=php");
// Bonus: Fetch and Parse a JSON web service
$results = json_decode(file_get_contents("http://search.twitter.com/search.json?&q=php"));
// Find minimum (or maximum) in a List
echo min(array(14, 35, -7, 46, 98))."\n";
echo max(array(14, 35, -7, 46, 98))."\n";
// Paralell Processing ... kind of
(($pid = pcntl_fork()) == -1 ? die("No forks, just spoons.") : ($pid ? pcntl_wait($status) : print_r("some heavy computation goes here\n")));
// Sieve of Eratosthenes ... skipped, not possible in one line, suggestions?
// FizzBuzz
for($i = 1; $i < 100; $i++) {
$matched = false;
if ($i % 3 == 0) { $matched = true; echo "Fizz"; }
if ($i % 5 == 0) { $matched = true; echo "Buzz"; }
if (!$matched) { echo $i; }
echo "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment