4335 posts
  • Has been part of the Envato Community for over 6 years
  • Has referred 1+ members
  • Has sold $1,000+ on Envato Market
  • Has been a beta tester for an Envato feature
+10 more
Reaper-Media says

Share on Twitter

Hi Guys!

First off, for those of you who don’t know me, my name’s Sam, and i’m the new community moderator for CodeCanyon. I thought i’d start off by creating a thread that hopefully quite a few people could benefit from.

The idea of this thread is to build up a list of good tips and tricks when it comes to using php that could proove useful in many scenarios. Feel free to also link to articles or tutorials that you think are useful. ( please don’t link to any free givaways though… :) ). Remember to place pieces of code within < pre > < /pre > tags so that they are formatted correctly on the forums, or similarly you could use a service like Pastie to paste large amounts of code in.

I’ll start off with a tip:

I find that when processing large arrays, and performing a function on each value of that array, if the number of items in the array is not going to change, it is always best to create a variable with the number of items in the array before the “for” structure:

i.e. Instead Of:
$myArray = array();
for($i=0;$i<sizeof($myArray);$i++){
    //Perform Action
};
Write This:
$myArray = array();
$arrayLength = sizeof($myArray);
for($i=0;$i<$arrayLength;$i++){
    //Perform Action
};
Or if you do not need to know the value of the incrementation variable, you could simply use this:
$myArray = array();
foreach($myArray as $value){
    //Perform Action
};

This only really matters when particularly large arrays are being processed and you need to optimise the execution of the php code.

Anyway guys, over to you. What php tips, tricks or links do you want to share? :)

Share!

Share on Twitter
296 posts
  • Has referred 1+ members
  • Has sold $1,000+ on Envato Market
  • Has collected 1+ items on Envato Market
  • Sells items exclusively on Envato Market
+2 more
theninja says
Wassup Sam !? Happy to have you as the new community moderator :)
This thread was looking bare so I decided to write a few quick tips, haha :D

I’ll start with one of my favourites… the shorthand if/else statements, otherwise known as ternary operators. Why write something in 20 lines when you can do it in much less ?
This is where ternary operators come in handy.
In it’s most basic form it’s written as “condition ? value if true : value if false” simples! (reference to british advert)
Here are a few examples :

Show an administration panel if admin is logged in, otherwise show a link to login page.
$sidePanel = $user->level == 'admin' ? file_get_contents('sidePanel.php') : '<a href="login.php">Admin login</a>';
Show a message with either a user’s name or “guest” depending if that person is logged in or not.
$welcome = 'Hi '.($user->logged_in ? $user->name : 'Guest').'!!!';
Adds an s to the number of hours a post has been posted if it’s above 1.
$timePosted = 'Posted '.$hour.' hour'.($hour != 1 ? 's' : '').' ago';
Redirect users that aren’t logged in to the login page.
header('Location: '.($user->logged_in ? 'index.php' : 'login.php')); exit;
They can also be nested within one another like those babushka doll thingies :D
(also too many of these and the code can become hard to read).
$welcome = 'Hi there! You'.($user->age > 18 ?  '\'re underage, therefore I\'m afraid you can\'t view this website.' : ($user->sex == 'male' ? ' handsome man!' : ' sexy minx!'));
This displays “Hi there! You’re underage, therefore I’m afraid you can’t view this website.” if you’re under 18, “Hi there! You handsome man!” if you’re a man over 18 and “Hi there! You sexy minx!” if you’re a woman above 18. Why? You may ask… I don’t know, it’s just an example, lol

Error Reporting, useful for site development.
error_reporting($testing ? E_STRICT : 0);

This is something I’ve personally never used but it’s good to know, I guess.
isset() can be used instead of strlen to check a string’s minimum length, in other words both of these are interchangeable :

if (strlen($string)>7) {
    // do something if the string's at least eight characters long.
}

if (isset($string[7])) {
    // do something if the string's at least eight characters long.
}
When you pass strings as an array each letter or character in the string is an element in that array.
So basically checking to see if he 7th element in this array exists you know if the string is at least 8 chars long (arrays start from 0, so $string7] is the 8th character in $string).
isset() is supposedly faster than strlen() as it’s a language construct and not a function, but I doubt it makes a huge difference.

Another useful part of php is, of course, the ol’ shorthand operators.
I think these are best explained by examples…
On the left is how you would write these normally and on the right is their shorthand form… $v1 and $v2 are just two mundane variables.

Arithmetic Operators :
Addition :          $v1 = $v1 + $v2        $v1 += $v2
Subtraction :       $v1 = $v1 - $v2        $v1 -= $v2
Multiplication :    $v1 = $v1 * $v2        $v1 *= $v2
Division :          $v1 = $v1 / $v2        $v1 /= $v2
Modulus :           $v1 = $v1 % $v2        $v1 %= $v2
Bitwise Operators :
Bitwise And :       $v1 = $v1 & $v2        $v1 &= $v2
Bitwise Or :        $v1 = $v1 | $v2        $v1 |= $v2
Bitwise Xor :       $v1 = $v1 ^ $v2        $v1 ^= $v2
Left shift :        $v1 = $v1 << $v2       $v1 <<= $v2
Right shift :       $v1 = $v1 >> $v2       $v1 >>= $v2
And lastly string Operators :
Concatenate :        $v1 = $v1 . $v2        $v1 .= $v2

If you’re a php developer it’s likely you know all these already but it’s nice to have them all written out in one place.
Anyway I’ll stop there as this post is long enough as it is, I hope these are useful to someone :)
190 posts
  • Has been part of the Envato Community for over 5 years
  • Has referred 10+ members
  • Has sold $10,000+ on Envato Market
  • Has collected 50+ items on Envato Market
+5 more
themac says

Hi there,

more Arithmetic Operators (echo example)
$i = 0;
Autoincrement     echo $i++;     //returns 0, increment $i
$i = 0;
Autoincrement     echo ++$i;     //returns 1, increment $i
$i = 0;
Autodecrement     echo $i--;     //returns 0, decrement $i
$i = 0;
Autodecrement     echo --$i;     //returns -1, decrement $i
debugging tipps:
for example
$sql = "insert into ...";
to check out the query you could use
$sql = "insert into ...";
echo $sql;
or faster:
echo $sql = "insert into ...";

hope that’s usefull for someone too :)

rgds
mac

499 posts
  • Has referred 1+ members
  • Has sold $1,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Located in Canada
+2 more
TutelageSystems says

Hi Guys,

Probably the biggest trick I use is the print_r / die combination.

If you have a variable, array, object etc that you need to look at before it goes into a function or comes out of a function you can use the following

$variable = $this->createObject(); // Fills $variable

print '< pre>';
print_r($variable);
print '< /pre>';
die;

Using the PRE tags gives the print_r some nice formatting allowing you to easily scan through and find what you are looking for (be sure to remove the space in the PRE tag. I had to add it because of the forum).

3261 posts
  • Helps us moderate the forums
  • Has been part of the Envato Community for over 5 years
  • Helped several times protecting Envato Market against copyright violations
  • Won a competition
+15 more
dtbaker Moderator says

Tip – creating alternating table row colours.

Love this one, use the idea in some way in almost every project.

Code:

Please see the pastie: http://pastie.org/929927 (problem with code in forum, edited by moderator)

using a combination of arithmetic ++ and modulus % with a ternary operator can be used to easily create alternating row classes. example of output:

<table>
 <tr class="odd">
   <td> ..... </td>
 </tr>
 <tr class="even">
   <td> ..... </td>
 </tr>
 <tr class="odd">
   <td> ..... </td>
 </tr>
</table>
3261 posts
  • Helps us moderate the forums
  • Has been part of the Envato Community for over 5 years
  • Helped several times protecting Envato Market against copyright violations
  • Won a competition
+15 more
dtbaker Moderator says

Tip – creating a table from a mysql query with X number of columns

If you ever need to display data in a gallery style table with X number of columns, here’s an easy way to do it:

First put whatever data you are trying to display into a temporary data structure (array) Below is an example of putting a mysql result set into a temporary array ready to display in a table.

// get all the photos from mysql that are part of gallery 123
$sql = "SELECT * FROM `photo_gallery_pictures` WHERE  `gallery_id` = '123'";
// temp array to store photo data structure 
$all_photos = array(); 
$res = mysql_query($sql);
// loop over the mysql result set, and place all results into our temporary array
while($row = mysql_fetch_assoc($res)){
   $all_photos [] = $row;
}

We now have all the photos from gallery 123 sitting in the $all_photos array. Time to display them in a nice HTML table.

<table>
  <?php $number_of_columns = 4;
  // we keep looping over our $all_photos array until there are no more photos to display
  // each time we display a photo, we remove it from $all_photos, until there are none left 
  while(count($all_photos)){  ?>
     <tr>
         <?php for($x=0;$x<$number_of_columns;$x++){     
         $photo_to_display = array_shift($all_photos);
         ?>
         <td>
              <?php if($photo_to_display){ ?>
              <img src="<?php echo $photo_to_display['image_source'];?>" />
              <p><?php echo $photo_to_display['image_description'];?></p>
              <?php } ?>
         </td>
         <?php } ?>
     </tr>
   <?php } ?>
</table>

This will spit out a table with max 4 columns and a photo in each table cell. If you run out of photos it will still print an empty table cell as to not affect any css styling etc…

4335 posts
  • Has been part of the Envato Community for over 6 years
  • Has referred 1+ members
  • Has sold $1,000+ on Envato Market
  • Has been a beta tester for an Envato feature
+10 more
Reaper-Media says

Thanks for the contributions so far guys! :)

443 posts
  • Has been part of the Envato Community for over 5 years
  • Has sold $1,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Sells items exclusively on Envato Market
+1 more
SplitV says
Tip – creating a table from a mysql query with X number of columns

If you ever need to display data in a gallery style table with X number of columns, here’s an easy way to do it:

First put whatever data you are trying to display into a temporary data structure (array) Below is an example of putting a mysql result set into a temporary array ready to display in a table.

// get all the photos from mysql that are part of gallery 123
$sql = "SELECT * FROM `photo_gallery_pictures` WHERE  `gallery_id` = '123'";
// temp array to store photo data structure 
$all_photos = array(); 
$res = mysql_query($sql);
// loop over the mysql result set, and place all results into our temporary array
while($row = mysql_fetch_assoc($res)){
   $all_photos [] = $row;
}

We now have all the photos from gallery 123 sitting in the $all_photos array. Time to display them in a nice HTML table.


  <?php $number_of_columns = 4;
  // we keep looping over our $all_photos array until there are no more photos to display
  // each time we display a photo, we remove it from $all_photos, until there are none left 
  while(count($all_photos)){  ?>
     
         <?php for($x=0;$x<$number_of_columns;$x++){     
         $photo_to_display = array_shift($all_photos);
         ?>
         
         <?php } ?>
     
   <?php } ?>
<?php if($photo_to_display){ ?>

<?php echo $photo_to_display[‘image_description’];?>

<?php } ?>
This will spit out a table with max 4 columns and a photo in each table cell. If you run out of photos it will still print an empty table cell as to not affect any css styling etc…

Can I ask why you do not just create the table within the first while loop. It would be more efficient to just have a counter and do everything within your first while loop. Initialize the counter before the loop to 0 and then increment it at the top of the loop. Then at the bottom of the while loop have a condition to spit out the

  <tr> </tr>
tags and reset the counter if counter equals your desired number of columns.

Also, I wouldn’t use a table in the first place to display a bunch of image thumbnails, I would just use divs with a float:left applied and all of the same width so they will naturally order themselves in visual columns dependent on the width of the containing element.

EDIT : Reaper can we create a javascript thread like this?

4335 posts
  • Has been part of the Envato Community for over 6 years
  • Has referred 1+ members
  • Has sold $1,000+ on Envato Market
  • Has been a beta tester for an Envato feature
+10 more
Reaper-Media says
EDIT : Reaper can we create a javascript thread like this?

I think we’ll leave it at just PHP for a couple of days, and see how it goes. Don’t forget to retweet it! ;)

When the time is right I’ll start a JavaScript one, and later on possibly an ASP or Rails or Python thread. Mail me if you have any ideas ;)

443 posts
  • Has been part of the Envato Community for over 5 years
  • Has sold $1,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Sells items exclusively on Envato Market
+1 more
SplitV says
Hi there, more Arithmetic Operators (echo example)
$i = 0;
Autoincrement     echo $i++;     //returns 0, increment $i
$i = 0;
Autoincrement     echo ++$i;     //returns 1, increment $i
$i = 0;
Autodecrement     echo $i--;     //returns 0, decrement $i
$i = 0;
Autodecrement     echo --$i;     //returns -1, decrement $i
debugging tipps:
for example
$sql = "insert into ...";
to check out the query you could use
$sql = "insert into ...";
echo $sql;
or faster:
echo $sql = "insert into ...";

hope that’s usefull for someone too :)

rgds
mac
var_dump is better alternative to just echoing/printing out variables when debugging. Escpecially useful for arrays and objects.

Helpful Information

  • Please read our community guidelines. Self promotion and discussion of piracy is not allowed.
  • Open a support ticket if you would like specific help with your account, deposits or purchases.
  • Item Support by authors is optional and may vary. Please see the Support tab on each item page.

Most of all, enjoy your time here. Thank you for being a valued Envato community member.

Post Reply

Format your entry with some basic HTML. Read the Full Details, or here is a refresher:

<strong></strong> to make things bold
<em></em> to emphasize
<ul><li> or <ol><li> to make lists
<h3> or <h4> to make headings
<pre></pre> for code blocks
<code></code> for a few words of code
<a></a> for links
<img> to paste in an image (it'll need to be hosted somewhere else though)
<blockquote></blockquote> to quote somebody

:grin: :shocked: :cry: Complete List of Smiley Codes

by
by
by
by
by
by