Skip to content

Instantly share code, notes, and snippets.

@mroffice
Last active February 15, 2016 13:27
Show Gist options
  • Save mroffice/54693a0eda9cebf8fb20 to your computer and use it in GitHub Desktop.
Save mroffice/54693a0eda9cebf8fb20 to your computer and use it in GitHub Desktop.
An overview of PHP, handy functions and debugging tips.

PHP

Debugging

When you want to learn a new framework or programming language, chances are you'll Google something like "how do i run php locally?" or "how do i make a blog with CakePHP?". Funnily enough, Google will provide you with results that tell you just that, but no more.

If you want to really learn and understand web development or the like, you need to actually know what's happening, rather than just knowing which buttons to hit to make magic happen.

You need to know how to interpret documentation, how to structure your application, how to keep your project under version control and, probably most importantly, you need to know how to debug.

These aren't topics that are easy to Google, nor are they as readily available online in easy tutorial format.

var_dump($var) will output information about the $var variable. String, array, class, whatever! In some cases (e.g. inside HTML select forms) var_dump doesn't show up. So how do you get it to work? You can put the output inside an HTML comment, or out put to a file.

$var = "Inside HTML comments, awesome!";

echo '<!--';
var_dump($var);
echo '-->';

// => <!--string(30) "Inside HTML comments, awesome!"-->
file_put_contents('debug.txt', print_r($var, true));

get_class($this) is handy for debugging so you know what class you're dealing with.

For quick and dirty dumping try dd():

dd($var);

Working with Objects and Arrays

Return the object in an array by property name:

> Array
> (
>     [0] => stdClass Object
>         (
>             [name] => Euan
>             [age] => 25
>         )
>     [1] => stdClass Object
>         (
>             [name] => Dan
>             [age] => 31
>         )
> )

$search = "Dan";

return array_filter(
  $array,
  function($a) use ($search)  {
    return $a->name === $search;
  }
);

> =>
> Array
> (
>     [1] => stdClass Object
>         (
>             [name] => Dan
>             [age] => 31
>         )
> )

Working with files

file_exists($file)

Returns true or false.

file_get_contents($file)

Returns the file in a string, or false.

fopen($file, $mode)

Mode Description
r Read only
w Write only
a Write only, but don't override
x New file, write only
r+ Read/write
w+ Read/write, will create a new file
a+ Read/write, but don't override
x+ New file, read/write

fread($file)

Returns the read string.

fread

fclose($file)

Closes the file.

Tips and Tricks

To see the PHP configuration, create a file with the contents:

<?php echo phpinfo(); ?>

Or, in the command line:

$ php -i

Analytics

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