homepage Welcome to WebmasterWorld Guest from 54.205.189.156
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

This 55 message thread spans 2 pages: 55 ( [1] 2 > >     
Php bag of tricks
Favorite php tricks on your site
copongcopong




msg:1316077
 11:05 pm on Nov 11, 2002 (gmt 0)

Hi everyone, I am reading on this thread ...

www.webmasterworld.com/forum21/3697.htm

and i find some simple php scripts that are very cheesey and said to myself why didn't i think about that!

How about posting your php tricks on your site like link management or everything under the sun which would be very helpful for all in creating dynamic sites and even for newbies.

peace. :)

[edited by: jatar_k at 4:10 pm (utc) on Mar. 29, 2003]

 

dhdweb




msg:1316078
 2:45 am on Nov 12, 2002 (gmt 0)

Did you call my script cheesie?, simple yes, cheesie no! :)

jatar_k




msg:1316079
 2:50 am on Nov 12, 2002 (gmt 0)

I don't think that is what copongcopong meant.

hmmm, tricks.

how about a little one to start. When you want to echo a var instead of using
<? echo $var;?>
use
<?= $var?>

a little quicker.

toadhall




msg:1316080
 3:31 am on Nov 12, 2002 (gmt 0)

Often times php coders argue over echoing non-php lines versus skipping in and out of php. Another option is to use print in somewhat the same way you'd use <pre> in html.
Try this:

<?
$str1 = "First half of the sentence";
$str2 = "and the second half.";
print "<html>
<head><title>Try It</title>
</head>
<body>
$str1 $str2
</body>
</html>";
?>

... the formatting of the code source will be as it appears in the php.

toadhall




msg:1316081
 6:25 am on Nov 12, 2002 (gmt 0)

Sometimes while coding you just want to have a quick look at the contents of an array.
To read keys and values without having to write while (list () = each) or array_walks and functions use print_r():

print_r($your_array);

..will result in this format:

Array ( [0] => value [1] => value [2] => value )

-or-

Array ( [key] => value [key] => value [key] => value )

Works on multi-dimensionals too.

Nick_W




msg:1316082
 8:44 am on Nov 12, 2002 (gmt 0)

If you have to print long blocks of html etc I like to do this:

$text=<<<EOF
<html>
blah
$someVar
blah
</html>
EOF;

Nick

NameNick




msg:1316083
 10:32 am on Nov 12, 2002 (gmt 0)

copongcopong:
How about posting your php tricks on your site like link management or everything under the sun which would be very helpful for all in creating dynamic sites and even for newbies.

That is exactly what I do since the last year. I collect all my little answers to questions in newsgroups, mailinglists, forums and boards and publish them on my Web site. Users are able to write comment - sometimes they enhance code or suggestions and sometimes they say just thanks ;)

It's a good thing - help other webmasters and building content for your site.

NN

andreasfriedrich




msg:1316084
 2:33 pm on Nov 12, 2002 (gmt 0)

echo '<pre>'; 
print_r($your_array);
echo '</pre>';

will work better for bigger arrays.

Andreas

andreasfriedrich




msg:1316085
 3:13 pm on Nov 12, 2002 (gmt 0)

trick

Use single quoted strings unless you need to interpolate variables into your string. This saves PHP the time to scan the string for contained variables and saves about 50% execution time.

data

double quotes: 0.001505970954895 
single quotes: 0.00078308582305908
difference...: 0.00072288513183594

benchmark

function getmicrotime($t) {  
list($usec, $sec) = explode(" ",$t);
return ((float)$usec + (float)$sec);
}
#
$start = microtime();
$a = array();
for($i=0;$i<100;$i++) {
array_push($a, "Aaron rules!");
}
$end = microtime();
$t1 = (getmicrotime($end) - getmicrotime($start));
echo "<pre>double quotes: $t1<br>";
#
unset($a);
#
$start = microtime();
$b = array();
for($i=0;$i<100;$i++) {
array_push($b, 'Aaron rules!');
}
$end = microtime();
$t2 = (getmicrotime($end) - getmicrotime($start));
$t3 = $t1-$t2;
echo "single quotes: $t2<br>difference...: $t3</pre>";

Andreas

andreasfriedrich




msg:1316086
 3:48 pm on Nov 12, 2002 (gmt 0)

trick

Use concatenation [php.net] rather than sprintf() [php.net]. Use sprintf [php.net] rather than interpolation [php.net].

Use sprintf [php.net] to build more complex strings such as SQL query strings.

data

concatenation: 0.0008620023727417 
sprintf......: 0.0017820596694946
interpolate..: 0.002047061920166

benchmark

$x = 'Aaron'; 
$y = 'C.';
$start = microtime();
for($i=0;$i<100;$i++) {
$a = $x . $y . ' rules!<br/>';
}
$end = microtime();
$t1 = (getmicrotime($end) - getmicrotime($start));
echo "<pre>concatenation: $t1<br>";
#
unset($a);
#
$start = microtime();
for($i=0;$i<100;$i++) {
$a = sprintf('%s %s rules!<br/>', $x, $y);
}
$end = microtime();
$t1 = (getmicrotime($end) - getmicrotime($start));
echo "<pre>sprintf......: $t1<br>";
#
unset($a);
#
$start = microtime();
for($i=0;$i<100;$i++) {
$a = "$x $y rules!<br/>";
}
$end = microtime();
$t2 = (getmicrotime($end) - getmicrotime($start));
$t3 = $t1-$t2;
echo "interpolate..: $t2<br>difference...: $t3</pre>";

comments

This is useful for all those who need to decide how to build their SQL strings since there is no way to prepare a statement using placeholders like there is in Perl using the DBI module.

While the concatenation method is the fastest it is hard to read and it scales not as good as the sprintf method. Look at the data using four variables:

concatenation: 0.0012750625610352 
sprintf......: 0.0018420219421387
interpolate..: 0.0027940273284912

Andreas

andreasfriedrich




msg:1316087
 3:58 pm on Nov 12, 2002 (gmt 0)

trick

Use push/join rather than concatenation.

data

using concat: 0.00052297115325928 seconds 
using array.: 0.00033998489379883 seconds
difference..: 0.00018298625946045 seconds

benchmark

$x = array('Taylor','Zac','Isaac','Leo','Aaron','Nick','Scott', 
'Dave','Bob','Clint','Chris','Thomas','Ryan','Dennis',
'Thimo','Steve');
#
$s1 = microtime();
foreach($x as $val) {
$s .= $val . ', ';
}
$e1 = microtime();
#
unset($s);
$s = array();
#
$s2 = microtime();
foreach($x as $val) {
array_push($s, $val);
}
$y = implode(', ', $s);
$e2 = microtime();
#
$t1 = (getmicrotime($e1) - getmicrotime($s1));
$t2 = (getmicrotime($e2) - getmicrotime($s2));
$td = $t1 - $t2;
#
echo "<pre>using concat: $t1 seconds<br>
using array.: $t2 seconds<br><br>
difference..: $td seconds</pre>";

Andreas

dingman




msg:1316088
 4:05 pm on Nov 12, 2002 (gmt 0)

Hmm. I'd never even thought about *why* I used single-quotes so much. I think it's just to reduce the number of possible changes to my string I have to think about, mostly. I never really thought about how much work that could save, but it sure makes sense that it would. I often take a pass on the next two tricks because I think that there are times when interpolation makes the code enough clearer to the next guy that it's worth the price, but that's clearly just a matter of what you choose to optimize for.

toadhall




msg:1316089
 6:04 pm on Nov 12, 2002 (gmt 0)

Don't remember where I got this, but many thanks to the originator. Forces a secure http connection:

<?
if (!($HTTPS == "on")) {
header ("Location: https://$SERVER_NAME$PHP_SELF");
exit;
}
?>

lorax




msg:1316090
 7:00 pm on Nov 12, 2002 (gmt 0)

Hey Andreas,
If you use "((float)$usec + (float)$sec)" you're mixing units (secs and microseconds).

Returns the string "msec sec" where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and msec is the microseconds part.

Shouldn't you convert one var to match the other?

andreasfriedrich




msg:1316091
 7:13 pm on Nov 12, 2002 (gmt 0)

Nope, lorax!

Both portions of the string are returned in units of seconds.

[php.net...]

Andreas

lorax




msg:1316092
 7:25 pm on Nov 12, 2002 (gmt 0)

Andreas,
Then why break it apart?

<edited>never mind I just figured it out</edited>

copongcopong




msg:1316093
 9:54 pm on Nov 12, 2002 (gmt 0)

dhdweb,

i find your scripts cool and that is what i meant when i say cheesey ... and i love cheese :)

thanks for the post everyone, lets keep it coming.

jatar_k




msg:1316094
 9:28 pm on Nov 13, 2002 (gmt 0)

something I have been using more of late which I like

Variable variables [php.net]

very useful tool.

dhdweb




msg:1316095
 10:07 pm on Nov 13, 2002 (gmt 0)

Thanks copongcopong,

I know you had no ill intentions, I was just trying to stir it up a little bit when I said that!

No hard feelings! :)

c3oc3o




msg:1316096
 4:35 pm on Nov 14, 2002 (gmt 0)

To copy andreas:

trick:
For outputting text with variables, use the little-known fact that echo allows several arguments, instead of concatenation or double quotes (which are twice as slow!):
echo 'text', $var, 'more text', $anothervar;

data:
commas.......: 0.0024470090866089
concatenation: 0.0028690099716187
double quotes: 0.0044499635696411

script:
<?
$x = 'H.'; $y = 'J.'; $z = 'O.';

$start = microtime();
for($i=0;$i<100;$i++) { echo $x, ' ', $y, ' ', $z, ' rules! '; }
$end = microtime();
$t1 = (getmicrotime($end) - getmicrotime($start));
unset($a);
#
$start = microtime();
for($i=0;$i<100;$i++) { echo $x.' '.$y.' '.$z.' rules! '; }
$end = microtime();
$t2 = (getmicrotime($end) - getmicrotime($start));
unset($a);
#
$start = microtime();
for($i=0;$i<100;$i++) { echo "$x $y $z rules! "; }
$end = microtime();
$t3 = (getmicrotime($end) - getmicrotime($start));
unset($a);
#
echo "<pre>commas.......: $t1<br></pre>";
echo "<pre>concatenation: $t2<br></pre>";
echo "<pre>double quotes: $t3</pre>";

function getmicrotime($t) {
list($usec, $sec) = explode(" ",$t);
return ((float)$usec + (float)$sec);
}
?>

andreasfriedrich




msg:1316097
 5:15 pm on Nov 14, 2002 (gmt 0)

Good point c3oc3o. Thereīs no point in letting PHP join the substrings before echoing them.

But donīt you think commata sounds so much nicer than commas. ;)

Iīm wondering who H.J.O might be? (Ha. Jo. Os. perhaps? Thatīs what Google suggested. If so then I have my doubts as to the truth value of such a statement as your script would produce. ;))

Andreas

c3oc3o




msg:1316098
 5:38 pm on Nov 14, 2002 (gmt 0)

Ha, just continuing the theme you set :) You got it right, by the way.

toadhall




msg:1316099
 6:18 pm on Nov 14, 2002 (gmt 0)

Pick a number between one and ten.

There must be an expression of some kind in an array's [].
$arr_foo[1];

That expression can be generated by a function, and the contents of the [], the expression, can be the function itself. So why not a function that returns a boolean result?

To wit:

With this array...
$colour = array("red","green");

And this function...
function which($x,$y){
return $x < $y;
}

You could echo your array thusly...
echo $colour[which($x,$y)];

With input from whatever...
$x = 4;
$y = 7;

And end up with "green" or "red" depending on the size relation of the two numbers.

But wait! There's more!

You could then add this array to the bgcolor of a table cell...
<table width="15%" border="0">
<tr>
<td bgcolor=<?=$colour[which($x,$y)];?>>
&nbsp;<br>
</td>
</tr>
</table>

And get a green light (Starboard!) or red (Make way, yuh swab.) all on the luck of the draw.

;)

andreasfriedrich




msg:1316100
 6:38 pm on Nov 14, 2002 (gmt 0)

That is an amazing piece of code toadhall. It could even be used to decide who is cooler: A.C. or H.J.O. ;)

Andreas

toadhall




msg:1316101
 7:03 pm on Nov 15, 2002 (gmt 0)

Variable functions.

Write a function...
function foo() {echo "You called foo()<br>\n";}

Stick it n a variable...
$func1 = foo();

And call the variable as a function...
$func1();

-o-

If the function takes an argument...
function bar($arg = '') {echo $arg . "ing! This is bar()<br>\n";}

So will the variable function (or should that be 'function variable'?)...
$func2 = bar();
$func2('Test');

NB - $10 to the first person who can find a good use for it.
(Jatar's paying)

jatar_k




msg:1316102
 7:50 pm on Nov 15, 2002 (gmt 0)

hehe,

variable functions, I am not totally sure what types of functions would need to be variable.

10$ CDN really isn't very much money to most of you. ;)

andreasfriedrich




msg:1316103
 9:03 pm on Nov 16, 2002 (gmt 0)

Write a function...
function foo() {echo "You called foo()<br>\n";}

Stick it n a variable...
$func1 = foo();

And call the variable as a function...
$func1();

This wonīt work the way you expect. In the line $func1 = foo(); $func1 is assigned the return value of foo. Since foo does not return anything $func1 does not contain a name of a function to call. This will result in an Call to undefined function error.

To use variable functions [php.net] in PHP all you do is assign the name of a function to call to a variable.

$func1 = 'foo';

This will work without the quotation marks as well (Due to the lack of any special meaning the bare word foo will be interpreted as a literal string) but you shouldnīt do that.

I am not totally sure what types of functions would need to be variable

This is what php.net has to say about the possible uses of variable functions:

Among other things, this can be used to implement callbacks, function tables, and so forth.

Andreas

andreasfriedrich




msg:1316104
 9:12 pm on Nov 16, 2002 (gmt 0)

<?php 
#
if (!isset($_GET['page']) or empty($_GET['page']))
$_GET['page'] = 'index';
#
$pages = array('index' => create_function('', 'echo "index";'),
'aaron' => 'aaron',
'jesse' => create_function('', <<<END
echo 'Jesse rules';
END
));
#
function aaron() {
echo "Aaron $args rules";
}
#
if (function_exists($pages[$_GET['page']])) {
$pages[$_GET['page']]();
} else {
echo 'page does not exist';
}
#
?>

One may build the function table prior to defining the functions since all one does is assign the name of a function. Resolution of which function to call is done at runtime. Variable functions are not function pointers nor are they references to functions.

If you call this script as script.php or script.php?page=index you get the index page. If you call it as script.php?page=aaron or script.php?page=jesse you get Aaronīs or Jesseīs page respectively. If you call it as script.php?page=nick there exists no corresponding function and the error message 'page does not exist' is displayed.

Andreas

toadhall




msg:1316105
 9:41 pm on Nov 16, 2002 (gmt 0)

Thanks Andreas. I did mis-speak myself.
Here's the original;

function foo() {echo "You called foo()<br>\n";}

function bar($arg = '') {echo $arg . "ing! This is bar()<br>\n";}

$func = 'foo';
$func();
$func = 'bar';
$func('Test');

Jatar: how much is $10 in Euros?

andreasfriedrich




msg:1316106
 9:55 pm on Nov 16, 2002 (gmt 0)

Iīm not Adam but here goes:

10 Canadian Dollar = 6.27 Euro

I failed to find a currency converter that uses GET to to transfer the data.

Andreas

This 55 message thread spans 2 pages: 55 ( [1] 2 > >
Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved