Skip to content

Instantly share code, notes, and snippets.

@smasty
Created June 6, 2011 22:33
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save smasty/1011261 to your computer and use it in GitHub Desktop.
Save smasty/1011261 to your computer and use it in GitHub Desktop.
10 PHP One Liners to Impress Your Friends - http://smasty.net/blog/10-php-oneliners
<? foreach(range(1, 10) as $i) echo $i * 2 . " ";
<? echo array_sum(range(1, 1000));
<?
$words = array("php", "foo", "framework", "apache", "nginx");
$tweet = "This is an example tweet talking about PHP and Apache.";
foreach($words as $word) if(stripos($tweet, $word) !== false) echo "$word\n";
<? echo file_get_contents("oneliners.php");
<? foreach(range(1, 4) as $i) echo "Happy Birthday " .($i == 3 ? "dear Martin" : "to You") . "\n";
<? foreach(array(49, 58, 76, 82, 88, 90) as $i) $i > 60 ? ($passed[] = $i) : ($failed[] = $i);
<? echo simplexml_load_file("http://search.twitter.com/search.atom?q=php")->asXML();
<?
echo min(array(14, 35, -7, 46, 98)) . "\n";
echo max(array(14, 35, -7, 46, 98)) . "\n";
<? ($pid = pcntl_fork()) == -1 ? exit(1) : ($pid ? hardCoreAction() && pcntl_wait($status) : hardCoreAction());
<?
// The idea by @tvlooy
// and a small bug fix by me.
foreach($p = range(2, 100) as $v) foreach(range(2, $v - 1) as $c) if(!($v % $c) && $v != 2) unset($p[$v - 2]);
echo join("\n", $p);
@tvlooy
Copy link

tvlooy commented Jun 27, 2011

number 10:

$p=range(2, 120);
foreach($p as $v)foreach(range(2,$v-1) as $c)if(!($v%$c))unset($p[$v]);
print_r($p);

@smasty
Copy link
Author

smasty commented Jun 27, 2011

@tvlooy: Thanks for your contributions!

@smasty
Copy link
Author

smasty commented Jun 27, 2011

@tvlooy: There was a small bug in your version.
You have to unset index $v - 2, because the range starts at two.
Also, number two is also a prime number, so it cannot be unset.

@tvlooy
Copy link

tvlooy commented Jun 27, 2011

ah yes, whoops :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment