Forum Moderators: coopster
I'm not a trained programmer but have been coding in php now since 2001 and feel that i'm at a good level and have been able to acheive very complex things in php where once i would have headed for the hills for sit down and an afternoons meditation.
However because of the route I (and many others i'm sure) have taken in coding on-demand, things have been missed out along that way, simple little code snippets that probably would have been taught to me had i gone the book/course approach.
So a little code snippet picked up recently that i haven't stopped using is the & symbol when calling a function.
This basically means that whatever happens to the variables inside the function, these values are automatically applied those variables outside the function that were passed to it.
example
<?php
function change_Namearray($array)
{
$ArraySize=sizeof($array);
for($i=0;$i<$ArraySize;$i++)
{
$array[$i].=' Is Great';
}
}$names=array('Jim','Sam','Fred');
change_Namearray($names); // NO & SIGN, thus no change
print_r($names);
/*
Prints
Array
(
[0] => Jim
[1] => Sam
[2] => Fred
)
*/change_Namearray(& $names); // NOTE THE & SIGN
print_r($names);
/*
Prints
Array
(
[0] => Jim Is Great
[1] => Sam Is Great
[2] => Fred Is Great
)
*/
?>
Anyone else got any useful snippets they've stumbled across and gone "darn(or other less polite words), that's useful"?
Hughie
As for contributing something, well, here's a quote from something I read along time ago, and it helps me make some decisions:
'Write legible, not clever, code.
Break down complex operations into distinct steps, avoid over nesting functions, and name your variables something that make sense.'
This applies to most things. But there are times where it may be necessary, or better, to be clever. ;)
Correct would be
<?php
function change_Namearray(&$array)
{
foreach($array as $key => $value)
{
$array[$key].=' Is Great';
}
}
$names=array('Jim','Sam','Fred');change_Namearray($names); // NO & SIGN, but changes
print_r($names);/*
Prints
Array
(
[0] => Jim Is Great
[1] => Sam Is Great
[2] => Fred Is Great
)
*/
For this use you could also use array_map [php.net]:
<?php
function is_great($name) {return $name.' Is Great';}$names=array('Jim','Sam','Fred');
$changed = array_map("is_great", $names);
print_r($changed);
?>
PS. And use the functions - they are there to be used:
Instead of many ifs and elseifs there is a switch;
Instead of sizeof array and for you can use foreach;
there are so many possibilities...
extract($someArray) is handy. (Imports the array elements into the current symbol table, eliminating the need to do like $elem1=$someArray['elem1'];$elem2=$someArray['elem2']... Also
basename($_SERVER['SCRIPT_NAME']) returns the current page file name quite nicely without any associated path info. basename($_SERVER['SCRIPT_NAME'],".php") will return the file name without its ".php" extension, if that's what it has ... Just a couple of functions I've learned about, recently ...