Monday, 14 October 2013

10 PHP code snippets for working with strings


Strings are a very important kind of data, and you have to deal with them daily with web development tasks. In this article, I have compiled 10 extremely useful functions and code snippets to make your php developer life easier.

Automatically remove html tags from a string

On user-submitted forms, you may want to remove all unnecessary html tags. Doing so is easy using the strip_tags() function:
$text = strip_tags($input, "");
Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2

Get the text between $start and $end

This is the kind of function every web developer should have in their toolbox for future use: give it a string, a start, and an end, and it will return the text contained with $start and $end.
function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}
Source: http://www.jonasjohn.de/snippets/php/get-between.htm

Transform URL to hyperlinks

If you leave a URL in the comment form of a WordPress blog, it will be automatically transformed into a hyperlink. If you want to implement the same functionality in your own website or web app, you can use the following code:
$url = "Jean-Baptiste Jung (http://www.webdevcat.com)";
$url = preg_replace("#http://([A-z0-9./-]+)#", '$0', $url);
Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2

Split text up into 140 char array for Twitter

As you probably know, Twitter only accepts messages of 140 characters or less. If you want to interact with the popular social messaging site, you’ll enjoy this function for sure, which will allow you to truncate your message to 140 characters.
function split_to_chunks($to,$text){
 $total_length = (140 - strlen($to));
 $text_arr = explode(" ",$text);
 $i=0;
 $message[0]="";
 foreach ($text_arr as $word){
  if ( strlen($message[$i] . $word . ' ') <= $total_length ){
   if ($text_arr[count($text_arr)-1] == $word){
    $message[$i] .= $word;
   } else {
    $message[$i] .= $word . ' ';
   }
  } else {
   $i++;
   if ($text_arr[count($text_arr)-1] == $word){
    $message[$i] = $word;
   } else {
    $message[$i] = $word . ' ';
   }
  }
 }
 return $message;
}
Source: http://www.phpsnippets.info/split-text-up-into-140-char-array-for-twitter

Remove URLs from string

When I see the amount of URLs people try to leave in my blog comments to get traffic and/or backlinks, I think I should definitely give a go to this snippet!
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);
Source: http://snipplr.com/view.php?codeview&id=15236

Convert strings to slugs

Need to generate slugs (permalinks) that are SEO friendly? The following function takes a string as a parameter and will return a SEO friendly slug. Simple and efficient!
function slug($str){
 $str = strtolower(trim($str));
 $str = preg_replace('/[^a-z0-9-]/', '-', $str);
 $str = preg_replace('/-+/', "-", $str);
 return $str;
}
Source: http://snipplr.com/view.php?codeview&id=2809

Parse CSV files

CSV (Coma separated values) files are an easy way to store data, and parsing them using PHP is dead simple. Don’t believe me? Just use the following snippet and see for yourself.
$fh = fopen("contacts.csv", "r");
while($line = fgetcsv($fh, 1000, ",")) {
    echo "Contact: {$line[1]}";
}
Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=1

Search for a string in another string

If a string is contained in another string and you need to search for it, this is a very clever way to do it:
function contains($str, $content, $ignorecase=true){
    if ($ignorecase){
        $str = strtolower($str);
        $content = strtolower($content);
    }
    return strpos($content,$str) ? true : false;
}
Source: http://www.jonasjohn.de/snippets/php/contains.htm

Check if a string starts with a specific pattern

Some languages such as Java have a startWith method/function which allows you to check if a string starts with a specific pattern. Unfortunately, PHP does not have a similar built-in function.
Whatever- we just have to build our own, which is very simple:
function String_Begins_With($needle, $haystack {
    return (substr($haystack, 0, strlen($needle))==$needle);
}
Source: http://snipplr.com/view.php?codeview&id=2143

Extract emails from a string

Ever wondered how spammers can get your email address? That’s simple, they get web pages (such as forums) and simply parse the html to extract emails. This code takes a string as a parameter, and will print all emails contained within. Please don’t use this code for spam ;)
function extract_emails($str){
    // This regular expression extracts all emails from a string:
    $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
    preg_match_all($regexp, $str, $m);

    return isset($m[0]) ? $m[0] : array();
}

$test_string = 'This is a test string...

        test1@example.org

        Test different formats:
        test2@example.org;
        <a href="test3@example.org">foobar</a>
        <test4@example.org>

        strange formats:
        test5@example.org
        test6[at]example.org
        test7@example.net.org.com
        test8@ example.org
        test9@!foo!.org

        foobar
';

print_r(extract_emails($test_string));
Source: http://www.jonasjohn.de/snippets/php/extract-emails.htm

Sunday, 1 September 2013

DocBlox ... use to generate API documentation in PHP

Using DocBlox

Until a few years ago, there were basically two tools you could use to generate API documentation in PHP: phpDocumentor and Doxygen. phpDocumentor was long considered the standard, with Doxygen getting notice when more advanced features such as inheritance diagrams are required. However, phpDocumentor is practically unsupported at this time (though a small group of developers is working on a new version), and Doxygen has never had PHP as its primary concern. As such, a number of new projects are starting to emerge as replacements.
One of these is DocBlox. I am well aware there are several others -- and indeed, I've tried several of them. This post is not here to debate the merits or demerits of this or other solutions; the intention is to introduce you to DocBlox so that you can evaluate it yourself.

Getting DocBlox

DocBlox can be installed in a variety of ways:
I personally prefer using the PEAR installer, as it's as simple as this:

prompt> pear channel-discover pear.michelf.com
prompt> pear channel-discover pear.docblox-project.org
prompt> pear install -a docblox/DocBlox-beta
The first channel-discover is to grab a third-party package optionally used in the rendering process to convert Markdown in the descriptions to HTML. And don't let the "beta" status fool you -- this project is quite stable at this point; the author, Mike van Riel, is simply being conservative as he rounds out features.
If you are checking out the project via Git or a snapshot, you simply need to expand the archive and make a note of its location -- when I've used this method in the past, I usually create a symlink to the bin/docblox.php script in my path:

prompt> ln -s path/to/docblox/bin/docblox.php ~/bin/docblox

Using DocBlox

Once you have installed DocBlox, how do you use it? It's really quite easy:

prompt> cd some/project/of/yours/
prompt> mkdir -p documentation/api/
prompt> docblox run -d path/to/source/ -t documentation/api/
At this point, DocBlox will merrily scan your source located in path/to/source, and build API documentation using its default HTML templates for you in documentation/api. Once complete, you can point your browser at documentation/api/index.html and start browsing your API documentation.

Using DocBlox to identify missing docblocks

While running, you may see some notices in your output stream, like the following:
2011-08-02T16:08:34-05:00 ERR (3): No DocBlock was found for Property $request in file Mvc/Route/RegexRoute.php on line 16
This output is invaluable for identifying places you've omitted docblocks in your code. You can capture this information pretty easily using tee:

prompt> docblox run -d path/to/source/ -t documentation/api/ 2>&1 | tee -a docblox.log
I recommend doing this whenever running DocBlox, going through the output, and adding docblocks wherever you encounter these errors.
(You can do similarly using tools such as PHP_CodeSniffer. More tools is never a bad thing, though.)
If you want to disable the verbosity, however, you can, by passing either the -q or --quiet options.

Class Diagrams

DocBlox will try and generate class diagrams by default. In order to do this, you need to have GraphViz installed somewhere on your path. The results are pretty cool, however -- you can zoom in and out of the diagram, and click on classes to get to the related API documentation.
(The class diagram is typically linked from the top of each page.)

Specifying an alternate title

By default, DocBlox uses its own logo and name as the title of the documentation and in the "header" line of the output. You can change this using the --title switch:

prompt> docblox run -d path/to/source/ -t documentation/api/ --title \"My Awesome API Docs\"

Using alternate templates

While the default template of DocBlox is reasonable, one of its initial selling points to me was the fact that you could conceivably create new templates. In order to test this out, and also iron out some of the kinks, Mike wrote templates for a few PHP OSS projects, including Zend Framework and Agavi. Templates need to be in a location DocBlox can find them -- in DocBlox/data/themes under your PEAR install, or simply data/themes if you installed a release tarball. Invoking a theme is as easy as using the --template argument:

prompt> docblox run -d path/to/source/ -t documentation/api/ --title \"My Awesome API Docs\" --template zend
Try out each of the provided themes to see which you might like best -- and perhaps try your hand at writing a theme. Each given theme is simply an XML file and a small set of XSL stylesheets, and optionally CSS and images to use with the generated markup.

Iterative documentation

When you generate documentation, DocBlox actually creates a SQLite database in which to store the information it learns while parsing your code base. This allows it to be very, very fast both when parsing (it can free information from memory once it's done analyzing a class or file) as well as when transforming into output (as it can iteratively query the database for structures).
What does this mean for you?
Well, first, if you want to try out new templates, it won't need to re-parse your source code -- it simply generates the new output from the already parsed definitions. This can be very useful particularly when creating new templates. Generation is oftentimes instantaneous for small projects.
Second, it means that you can build the full documentation once, and only periodically update it (which you can do using the --force option). This is particularly useful for build processes.

Configuration

One problem with any rich CLI tool is that you often get a proliferation of options, and remembering them between invocations can be hard (particularly if you only run the tool during releases). DocBlox allows you to create a configuration file, docblox.xml, in your project. The format is relatively simple; the (mostly) equivalent to the above options I've used is as below:

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>                                     
<docblox>
    <parser>
        <target>documentation/api</target>
    </parser>
    <transformer>
        <target>documentation/api</target>
    </transformer>
    <files>
        <directory>path/to/source</directory>
    </files>
    <transformations>
        <template>
            <name>zend</name>
        </template>
    </transformations>
</docblox>
You can't specify the title in the configuration, but often that will be template-driven, anyways.
DocBlox will then look for this file in the current directory and simply use it, allowing you to invoke it as follows:

prompt> docblox run
Or you can specify the configuration file yourself:

prompt> docblos run -c config.xml
(Side note: on the release current as of when I write, 0.12.2, I have not successfully been able to specify the template name.)

Search

If you look carefully at the generated output, you'll notice a search box. By default, this doesn't work... because it points to a PHP script! When installed on a server capable of serving PHP, however, it can be used to help find classes, methods, and more. As an example, you can search the Zend Framework 1.11 API documentation.

Conclusions

Hopefully this tutorial will get you started investigating DocBlox. I've been quite happy with what I've seen so far of the project, and gladly recommend it. There are other alternatives, however, and I also suggest you try those out; Liip recently published a comparison of features, and that article can be used as a starting point for your own investigations.
(Disclosure : Mike van Riel, he's developed DocBlox).

Saturday, 31 August 2013

Enable and Install cURL in Apache -Ubuntu

apache

This extension for PHP allows for behind the scenes communication between php pages.  This can come in handy if you are needing to communicate or send information between clients and servers.  Following are the steps need to install and test the extension on an Ubuntu Apache web server.

Install Components


sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

Restart the Server


sudo service apache2 restart

Create a test page on the computer to ensure that everything is working.
test.php
<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>
browse to the page and make sure there are no errors

Wednesday, 21 August 2013

php tomezone related troubleshooting

Warning: socket_bind() [function.socket-bind]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Asia/Calcutta' for 'IST/5.0/no DST' instead in /var/www/chat_php.php on line 19



solution:-

try this
 

date_default_timezone_set('Asia/Calcutta');
 




At beginning your php file.

Friday, 16 August 2013

Laravel Quickstart (PHP framework)

Installation#

To install the Laravel framework, you may issue the following command from your terminal:
composer create-project laravel/laravel your-project-name --prefer-dist
Or, you may also download a copy of the repository from Github. Next, after installing Composer, run the composer install command in the root of your project directory. This command will download and install the framework's dependencies.
After installing the framework, take a glance around the project to familiarize yourself with the directory structure. The app directory contains folders such as views, controllers, and models. Most of your application's code will reside somewhere in this directory. You may also wish to explore the app/config directory and the configuration options that are available to you.

Routing#

To get started, let's create our first route. In Laravel, the simplest route is a route to a Closure. Pop open the app/routes.php file and add the following route to the bottom of the file:
Route::get('users', function()
{
    return 'Users!';
});
Now, if you hit the /users route in your web browser, you should see Users! displayed as the response. Great! You've just created your first route.
Routes can also be attached to controller classes. For example:
Route::get('users', 'UserController@getIndex');
This route informs the framework that requests to the /users route should call the getIndex method on the UserController class. For more information on controller routing, check out the controller documentation.

Creating A View#

Next, we'll create a simple view to display our user data. Views live in the app/views directory and contain the HTML of your application. We're going to place two new views in this directory: layout.blade.php and users.blade.php. First, let's create our layout.blade.php file:
<html>
    <body>
        <h1>Laravel Quickstart</h1>

        @yield('content')
    </body>
</html>
Next, we'll create our users.blade.php view:
@extends('layout')

@section('content')
    Users!
@stop
Some of this syntax probably looks quite strange to you. That's because we're using Laravel's templating system: Blade. Blade is very fast, because it is simply a handful of regular expressions that are run against your templates to compile them to pure PHP. Blade provides powerful functionality like template inheritance, as well as some syntax sugar on typical PHP control structures such as if and for. Check out the Blade documentation for more details.
Now that we have our views, let's return it from our /users route. Instead of returning Users! from the route, return the view instead:
Route::get('users', function()
{
    return View::make('users');
});
Wonderful! Now you have setup a simple view that extends a layout. Next, let's start working on our database layer.

Creating A Migration#

To create a table to hold our data, we'll use the Laravel migration system. Migrations let you expressively define modifications to your database, and easily share them with the rest of your team.
First, let's configure a database connection. You may configure all of your database connections from the app/config/database.php file. By default, Laravel is configured to use MySQL, and you will need to supply connection credentials within the database configuration file. If you wish, you may change the driver option to sqlite and it will use the SQLite database included in the app/database directory.
Next, to create the migration, we'll use the Artisan CLI. From the root of your project, run the following from your terminal:
php artisan migrate:make create_users_table
Next, find the generated migration file in the app/database/migrations folder. This file contains a class with two methods: up and down. In the up method, you should make the desired changes to your database tables, and in the down method you simply reverse them.
Let's define a migration that looks like this:
public function up()
{
    Schema::create('users', function($table)
    {
        $table->increments('id');
        $table->string('email')->unique();
        $table->string('name');
        $table->timestamps();
    });
}

public function down()
{
    Schema::drop('users');
}
Next, we can run our migrations from our terminal using the migrate command. Simply execute this command from the root of your project:
php artisan migrate
If you wish to rollback a migration, you may issue the migrate:rollback command. Now that we have a database table, let's start pulling some data!

Eloquent ORM#

Laravel ships with a superb ORM: Eloquent. If you have used the Ruby on Rails framework, you will find Eloquent familiar, as it follows the ActiveRecord ORM style of database interaction.
First, let's define a model. An Eloquent model can be used to query an associated database table, as well as represent a given row within that table. Don't worry, it will all make sense soon! Models are typically stored in the app/models directory. Let's define a User.php model in that directory like so:
class User extends Eloquent {}
Note that we do not have to tell Eloquent which table to use. Eloquent has a variety of conventions, one of which is to use the plural form of the model name as the model's database table. Convenient!
Using your preferred database administration tool, insert a few rows into your users table, and we'll use Eloquent to retrieve them and pass them to our view.
Now let's modify our /users route to look like this:
Route::get('users', function()
{
    $users = User::all();

    return View::make('users')->with('users', $users);
});
Let's walk through this route. First, the all method on the User model will retrieve all of the rows in the users table. Next, we're passing these records to the view via the with method. The with method accepts a key and a value, and is used to make a piece of data available to a view.
Awesome. Now we're ready to display the users in our view!

Displaying Data#

Now that we have made the users available to our view. We can display them like so:
@extends('layout')

@section('content')
    @foreach($users as $user)
        <p>{{ $user->name }}</p>
    @endforeach
@stop
You may be wondering where to find our echo statements. When using Blade, you may echo data by surrounding it with double curly braces. It's a cinch. Now, you should be able to hit the /users route and see the names of your users displayed in the response.
This is just the beginning. In this tutorial, you've seen the very basics of Laravel, but there are so many more exciting things to learn. Keep reading through the documentation and dig deeper into the powerful features available to you in Eloquent and Blade. Or, maybe you're more interested in Queues and Unit Testing. Then again, maybe you want to flex you

Friday, 9 August 2013

The top 10 most-used PHP features

1. PDO Class

We use the PDO (PHP Data Object) exclusively for connecting to our MySQL databases. PDO provides a nice abstraction layer around a set of database drivers such as MySQL, PostgreSQL and MS SQL. This means that whichever database you are using, as long as PDO supports it, you can use the same functions to perform the same actions on the database. This makes your code more portable for your web application to be used on a whole range of databases with no extra development time.
The PDO Class provides many standardised functions such as creating transactions, creating prepared statements and allowing you to escape your variables if you need to. Used in the correct way, PDO can help protect your web application from SQL injection attacks.
The PDO class can be used directly, but we like to use our own layer over the top to give us more control over things like data entry formatting and validation, which the PDO class does not provide. RedBeanPHP ORM is a good open source solution that provides some nice functionality that's built on top of PDO.
The example below shows a connection to a MySQL database that selects the name, colour and calories from each row in fruit table. By using a prepared statement, PDO converts the placeholders to match the array that is parsed in the execute function. By using the prepared statement, all the values are escaped to protect from SQL injection. The whole piece of code has been added to a try block, which can be used to catch any exceptions.
  1. <?php
  2. try{
  3.     /* Connect to Database */
  4.     $dsn = 'mysql:dbname=test;host=localhost';
  5.     $dbh = new PDO($dsn,'username','password');
  6.  
  7.     /* Create SQL String with parameters */
  8.     $sql = 'SELECT name, colour, calories
  9.    FROM fruit
  10.    WHERE calories < :calories AND colour = :colour';
  11.     $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
  12.     /* add values and execute request on database */
  13.     $sth->execute(array(':calories' => 150, ':colour' => 'red'));
  14.     /* Get the returned Data */
  15.     $dataSet = $sth->fetchAll();
  16.     /* Print Results */
  17.     print_r($dataSet);
  18.  
  19. }catch (PDOException $e){
  20.     echo 'PDO Error: '.$e->getMessage();
  21. }catch(Exception $e){
  22.     echo 'A Unknown Error Occurred: '.$e->getMessage();
  23. }

2. json_encode & json_decode

With the rollout of PHP5.2 came two very useful functions that allow you to parse JSON (JavaScript Object Notation) strings. JSON is a text-based standard that is generally used to send and receive data with a simple structure that was designed to be easily read, both by a computer and by a human.
PHP provides two functions that allow you to manipulate your data both to and from JSON. json_encode is utilised by setting the first argument as your data. Be that a simple string or a multi dimensional array, PHP will try to return a string of your data that has been converted to a JSON formatted string. This string can then be used to output on an API or included in your HTML template to be read by your JavaScript code on the front end.
There are some caveats to using json_encode. For example, only basic data types can be used. Strings, numbers and Booleans are the main types along with associative and non-associative arrays. PHP will also try to convert class objects but will only encode public properties. UTF8 is also used to encode the resulting string of JSON.
The example below shows an array of animals that is converted to a JSON string then sent to the user. You could call this script from an Ajax request via a JavaScript framework which will then return a JavaScript object ready for you to iterate over.
  1. <?php
  2. /* Set Content Encoding Header */
  3. header('Content-type: application/json; charset=utf-8');
  4. /* Array of animals*/
  5. $myArray = array(
  6.     array('type'=>'cat','name'=>'Alfie','age'=>2),
  7.     array('type'=>'dog','name'=>'Bella','age'=>6)
  8. );
  9. /* Encode to JSON */
  10. $jsonString = json_encode($myArray);
  11. echo $jsonString;
json_decode is the opposite of json_encode. The function takes the JSON string as the first argument and tries to parse the string into a PHP variable. There is an optional second argument to convert the string to an object or an associative array. By parsing ‘true’ as the second argument (as shown below) you can return an array.
  1. <?php
  2. /* Set Content Encoding Header */
  3. $json = '[{"type":"cat","name":"Alfie","age":2},{"type":"dog","name":"Bella","age":6}]';
  4. /* Parse JSON to Object */
  5. $object = json_decode($json);
  6. /* Parse JSON to Array */
  7. $array = json_decode($json,true);
  8. /* Print Object */
  9. var_dump($object);
  10. /* Print Array */
  11. var_dump($array);
The advantage of using JSON over XML is its simplicity; with only a few data types PHP makes it very easy to parse simple data. JSON may not be as fast as the XML parsing in the majority of cases, but json_decode provides you with direct access to your data in an array or object format. This is unlike simpleXML, which returns a simpleXML object which you then have to process further to gain access to your data. Consequently, json_decode can be considered to be just as fast.

3. DateTime Class

The DateTime class allows you to manage time and dates in a more object-ordinated way, which is impossible using the standard core functions such as mktime and strtotime. By utilising the DateInterval and DateTimeZone classes, we are able to perform standard functionality like adding or subtracting time intervals on a date or changing the current time zone. The DateTime class can also be extended so we can provide extra functionality whilst making code cleaner and easier to read.
An important reason to use the DateTime class is that it stores all the dates as a 64-bit integer, which provides a workaround for the 32-bit 2038 bug where the dates will cease it increase any further.
The code example below demonstrates how the DateTime Class can be used to add a day to the current server time then convert the time zone to UTC.
  1. <?php
  2. /* Get server time*/
  3. $date = new DateTime();
  4. echo $date->format('Y-m-d H:i:s');
  5. /* Add 1 Day */
  6. $date->add(new DateInterval('P1D'));
  7. echo '<br>'.$date->format('Y-m-d H:i:s');
  8. /* Change Timezone to UTC */
  9. $date->setTimezone(new DateTimeZone('etc/UTC'));
  10. echo '<br>'.$date->format('Y-m-d H:i:s');

4. Exceptions

With PHP5 came the implementation of exceptions. Like other programming languages such as Java and C#, exceptions are used to 'throw' errors that can be caught at any point by bubbling up through your code stack. An exception can be created easily using the throw keyword followed by an Exception object.
Catching exceptions is implemented by wrapping the code you want to test in try block. You will then need to create a catch block to 'catch' any exception that the code in the try block throws.
The PHP interpreter will try and parse everything in the block as usual. If no exception is thrown, then the interpreter will continue down the script ignoring anything in the catch block. However, if an exception is thrown, the rest of the code in the try block is ignored and will execute everything in the catch block.
The beauty of exceptions is that they can be extended as they are just classes. By extending the standard Exception class you can give extra functionality to your exception. Another advantage of extending Exceptions is that it allows you to have multiple catch blocks that can refer to each exception class by utilising type hinting.
With PHP5.5, we are now given a third block called finally. Any code in this area will be run regardless of whether there has been an exception thrown or not.
Like in the PDO example, the example below is contained in a try block. If the script fails to connect for any reason then we are able to capture that by introducing a catch block to capture any PDOExceptions or Exceptions. In the case below any errors will be printed to the screen and the script will still be executed to the end.
  1. <?php
  2. try{
  3.     $dsn = 'mysql:dbname=test;host=localhost';
  4.     $dbh = new PDO($dsn,'username','password');
  5.     echo 'Connected to Database';
  6. }catch (PDOException $e){
  7.     echo 'Connection Failed: '.$e->getMessage();
  8. }catch(Exception $e){
  9.     echo 'A Unknown Error Occurred: '.$e->getMessage();
  10. }
  11. echo 'I am still parsed, even if there was an error';

5. Namespaces

In the times before namespaces, PHP put every variable, function and class under the global namespace. This limited developers to ensure that their applications only had unique function and class names. Developers got round this issue by prefixing class and function names to provide a pseudo effect of namespaces, but the problem with this was that class names could end up being huge, making it sometime hard to read and write them without the use of an intelligent IDE.
Thankfully, with the introduction of namespaces, this problem was resolved. By using the namespace keyword followed by the namespace name at the top of a PHP file, it puts all the code below into that reflective namespace that cannot be accessed by any other namespaces unless explicitly instructed to. With the use of namespaces, we are now able to create well-structured and readable code that's easier to read and manage.
The example below shows how we can implement our own myNamespace namespace and create a new DateTime Class that is completely independent from the standard one provided in the global namespace. Notably, we are able to still use the default standard DateTime class in the namespace by adding a backslash to the front of the name when creating a new instance.
  1. <?php
  2. namespace myNamespace;
  3.  
  4. class DateTime{
  5.     public function customMethod(){
  6.         return 'Fun Times';
  7.     }
  8. }
  9. /*
  10.  * Create a new DateTime object that's in this current namespace
  11.  * If we are outside this namespace we can create it by:  
  12.  *        $customDate = new \myNamespace\DateTime();
  13.  */
  14. $customDate = new DateTime();
  15. echo $customDate->customMethod();
  16. /* We can still create the default DateTime object */
  17. $standardDate = new \DateTime();
  18. echo $standardDate->format('Y-m-d H:i:s');

6. Usort

usort allows the developer to sort an array based on a compare function that's configurable by the developer. This allows you to create more complex sorting algorithms that are not provided by the standard core array sort functions.
The callback/closure function has two parameters, which are two items in the array you have asked to sort on. It's then for you to decide if the first argument is greater, smaller or equal to the second argument. This is done by returning an integer value. Anything smaller than zero will assume the first argument is smaller than the second. Zero means the arguments are equal. Greater than zero means the first argument is larger than the second.
One great application for usort that we tend to use on a daily basis is to sort a simple multi-dimensional array. For example, let's say we have an array of students that consists of an associative array of name and age. By using the usort function along with a callback/closure function, we are able to pick the age and sort by ascending or descending.
For example, the code below is sorting by the age variable for each student in the students array. The callback/closure function provides the algorithm that compares the two ages and decides if the first age is greater than the second.
  1. <?php
  2.  
  3. $successful = usort($students, function  ($a, $b) {
  4.     return $a['age'] - $b['age'];
  5. });

7. Hashing API

There was an issue not too long ago with big-name sites getting hacked and insecure hashed passwords getting stolen. Back in the day, using the MD5 function was sufficient to hash a password, so it was secure. The problem with MD5 and SHA1 is that they are fast to perform the hashing algorithm. Along with the invention of faster processors and the utilisation of GPUs, people have the ability to process many hundreds of thousands of hashes per second, even on a standard desktop computer or laptop.
The new hashing API introduced in PHP5.5 provides an easy-to-use layer on top of bcrypt to create secure (for now) hashes that are a lot harder to solve by hackers. The example below shows how any string variable can be hashed. A salt will be created automatically and the hashing routing will have a cost of 15. The cost will make the hashing more secure but slower to complete.
  1. <?php
  2. $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 20]);

8. SimpleXML Class

When we have to deal with XML files we tend to use the SimpleXML class. This easy-to-use class gives you the ability to read and edit XML files via objects. Using these objects gives you the ability to return values and iterate over arrays in the usual ways, as well as a set of simple methods to modify the XML’s structure. If you just need to grab something specific in the XML then using the built-in method of XPath, you can return a set of SimpleXML Element objects for just the path that you provided.
As well as reading XML, SimpleXML also provides the methods to create new documents and/or inject elements back into the imported XML. This can then be saved all in a few lines of code.
The SimpleXML class is provided as a standard extension for PHP. Although it’s not in the core of PHP, it is enabled by default.
The example below shows a very simple example to get a list of public photos from Flickr and display the content html of each photo.
  1. <?php
  2. /* Load flickr Public Feed */
  3. $xml = simplexml_load_file('http://api.flickr.com/services/feeds/photos_public.gne');
  4. if(is_object($xml)){
  5.     /* Get each entry and echo the content tag */
  6.     foreach($xml->entry as $photo) echo $photo->content;
  7. }

9. glob

The glob function provides an easy one-line solution for creating an array of path names using a pattern you provide. glob may not be as fast as using the opendir and readdir combination, but if you just want to iterate over a directory, or you’re searching for a specific file type such as an image, then using glob could be a good solution to your problem.
The first argument is a glob pattern string that's similar to a regular expression in the way that it functions, but the syntax to create the pattern has some differences. This allows you to search for a varied subset of files and folders that are contained in a directory.
One big disadvantage of using glob is that all the results are stored into memory in one go. If you have a very large folder full of files you can soon run out of memory, and in this instance, it would be better to use opendir and readdir as it creates a read stream buffer.
Using the example below we are able to return all the image files in the $imagePath directory. An array will be returned to the $images variable.
  1. <?php
  2. /* Find all image files in image folder */
  3. $images = glob($imagePath.'*.{gif,jpeg,jpg,png}',GLOB_BRACE);

10. array_map

The standard core functions that PHP provide tend to perform faster, than creating your own similar functions using PHP code. A great example of this is utilising array_map instead of creating a for or which loop. array_map allows you to create a function called a callback that will be applied to every item in an array you supply.
For example, if you had an array of lowercase letters, a callback function can be created to uppercase all the characters in the array. On a small-sized array, the speed increase would be quite small, but once you start using larger arrays, you can really see a significant difference in speed.
In the example below we are converting the alphabet from lowercase to uppercase. We have provided the array_map function with a string of the name of the function we want to process. In this case we are using strtoupper to convert each letter in the array.

If there’s a need for more complex functionality, we can also provide the array_map function, a closure like in the usort example above.
  1. <?php
  2. $alphabet=array();
  3. /* Create lower Case Alphabet */
  4. for($i=97;$i<123;$i++) $alphabet[]=chr($i);
  5. /* Convert to Uppercase */
  6. $upperCaseAlphabet = array_map('strtoupper',$alphabet);

Expert badge

There are endless possibilities with PHP, but it’s not until you fully grasp the base features covered in this article that you fully begin to earn your PHP expert badge. It can be a long and steep learning curve but it’s a worthwhile one. PHP forms the foundations of so much of our work at Ecce Media, from building bespoke platforms and ecommerce systems, to content management systems and so much more. In the world of web development, every day brings a new challenge and armed with PHP and our top tips, you’ll be in prime position to tackle them.

Thursday, 8 August 2013

natsort : natural sort for array

natsort

(PHP 4, PHP 5)
natsortSort an array using a "natural order" algorithm

reject note Description

bool natsort ( array &$array )
This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in sort()) can be seen in the example below.

reject note Parameters

array
The input array.

reject note Return Values

Returns TRUE on success or FALSE on failure. 

Example #1 natsort() examples demonstrating basic usage
<?php
$array1 
$array2 = array("img12.png""img10.png""img2.png""img1.png");
asort($array1);
echo 
"Standard sorting\n";print_r($array1);
natsort($array2);
echo 
"\nNatural order sorting\n";print_r($array2);?>
The above example will output:
Standard sorting
Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

Sorting Arrays

PHP has several functions that deal with sorting arrays, and this document exists to help sort it all out.
The main differences are:
  • Some sort based on the array keys, whereas others by the values: $array['key'] = 'value';
  • Whether or not the correlation between the keys and values are maintained after the sort, which may mean the keys are reset numerically (0,1,2 ...)
  • The order of the sort: alphabetical, low to high (ascending), high to low (descending), numerical, natural, random, or user defined
  • Note: All of these sort functions act directly on the array variable itself, as opposed to returning a new sorted array
  • If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).
Sorting function attributes
Function name Sorts by Maintains key association Order of sort Related functions
array_multisort() value associative yes, numeric no first array or sort options array_walk()
asort() value yes low to high arsort()
arsort() value yes high to low asort()
krsort() key yes high to low ksort()
ksort() key yes low to high asort()
natcasesort() value yes natural, case insensitive natsort()
natsort() value yes natural natcasesort()
rsort() value no high to low sort()
shuffle() value no random array_rand()
sort() value no low to high rsort()
uasort() value yes user defined uksort()
uksort() key yes user defined uasort()
usort() value no user defined uasort()

Wednesday, 7 August 2013

17 useful functions for manipulating arrays in PHP

This document outlines some of the more useful functions in the PHP array toolkit, and features detailed explanations and usage examples.
Like arrays in other languages, PHP arrays allow you to store multiple values in a single variable and operate on them as a set. PHP offers an extensive array manipulation toolkit—over 60 functions—that lets you process arrays in almost any way imaginable including reversing them, extracting subsets, comparing and sorting, recursively processing, and searching them for specific values.
This document outlines some of the more useful functions in the PHP array toolkit, with explanations and usage examples:

This table is also available as free downloadable PDF.


Function
Explanation
Example
sizeof($arr)
This function returns the number of elements in an array.
Use this function to find out how many elements an array contains; this information is most commonly used to initialize a loop counter when processing the array.
Code:
$data = array("red", "green", "blue");

echo "Array has " . sizeof($data) . " elements";
?>

Output:
Array has 3 elements
array_values($arr)
This function accepts a PHP array and returns a new array containing only its values (not its keys). Its counterpart is the array_keys() function.
Use this function to retrieve all the values from an associative array.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_values($data));
?>

Output:
Array
(
[0] => Holmes
[1] => Moriarty
)
array_keys($arr)
This function accepts a PHP array and returns a new array containing only its keys (not its values). Its counterpart is the array_values() function.
Use this function to retrieve all the keys from an associative array.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_keys($data));
?>

Output:
Array
(
[0] => hero
[1] => villain
)
array_pop($arr)
This function removes an element from the end of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_pop($data);
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
)
array_push($arr, $val)
This function adds an element to the end of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_push($data, "Harry");
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)
array_shift($arr)
This function removes an element from the beginning of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_shift($data);
print_r($data);
?>

Output:
Array
(
[0] => Jim
[1] => Tom
)
array_unshift($arr, $val)
This function adds an element to the beginning of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_unshift($data, "Sarah");
print_r($data);
?>

Output:
Array
(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
each($arr)
This function is most often used to iteratively traverse an array. Each time each() is called, it returns the current key-value pair and moves the array cursor forward one element. This makes it most suitable for use in a loop.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
while (list($key, $value) = each($data)) {
echo "$key: $value \n";
}
?>

Output:
hero: Holmes
villain: Moriarty
sort($arr)
This function sorts the elements of an array in ascending order. String values will be arranged in ascending alphabetical order.
Note: Other sorting functions include asort(), arsort(), ksort(), krsort() and rsort().
Code:
$data = array("g", "t", "a", "s");
sort($data);
print_r($data);
?>

Output:
Array
(
[0] => a
[1] => g
[2] => s
[3] => t
)
array_flip($arr)
The function exchanges the keys and values of a PHP associative array.
Use this function if you have a tabular (rows and columns) structure in an array, and you want to interchange the rows and columns.
Code:
$data = array("a" => "apple", "b" => "ball");
print_r(array_flip($data));
?>

Output:
Array
(
[apple] => a
[ball] => b
)
array_reverse($arr)
The function reverses the order of elements in an array.
Use this function to re-order a sorted list of values in reverse for easier processing—for example, when you're trying to begin with the minimum or maximum of a set of ordered values.
Code:
$data = array(10, 20, 25, 60);
print_r(array_reverse($data));
?>

Output:
Array
(
[0] => 60
[1] => 25
[2] => 20
[3] => 10
)
array_merge($arr)
This function merges two or more arrays to create a single composite array. Key collisions are resolved in favor of the latest entry.
Use this function when you need to combine data from two or more arrays into a single structure—for example, records from two different SQL queries.
Code:
$data1 = array("cat", "goat");
$data2 = array("dog", "cow");
print_r(array_merge($data1, $data2));
?>

Output:
Array
(
[0] => cat
[1] => goat
[2] => dog
[3] => cow
)
array_rand($arr)
This function selects one or more random elements from an array.
Use this function when you need to randomly select from a collection of discrete values—for example, picking a random color from a list.
Code:
$data = array("white", "black", "red");
echo "Today's color is " . $data[array_rand($data)];
?>

Output:
Today's color is red
array_search($search, $arr)
This function searches the values in an array for a match to the search term, and returns the corresponding key if found. If more than one match exists, the key of the first matching value is returned.
Use this function to scan a set of index-value pairs for matches, and return the matching index.
Code:
$data = array("blue" => "#0000cc", "black" => "#000000", "green" => "#00ff00");
echo "Found " . array_search("#0000cc", $data);
?>

Output:
Found blue
array_slice($arr, $offset, $length)
This function is useful to extract a subset of the elements of an array, as another array. Extracting begins from array offset $offset and continues until the array slice is $length elements long.
Use this function to break a larger array into smaller ones—for example, when segmenting an array by size ("chunking") or type of data.
Code:
$data = array("vanilla", "strawberry", "mango", "peaches");
print_r(array_slice($data, 1, 2));
?>

Output:
Array
(
[0] => strawberry
[1] => mango
)
array_unique($data)
This function strips an array of duplicate values.
Use this function when you need to remove non-unique elements from an array—for example, when creating an array to hold values for a table's primary key.
Code:
$data = array(1,1,4,6,7,4);
print_r(array_unique($data));
?>

Output:
Array
(
[0] => 1
[3] => 6
[4] => 7
[5] => 4
)
array_walk($arr, $func)
This function "walks" through an array, applying a user-defined function to every element. It returns the changed array.
Use this function if you need to perform custom processing on every element of an array—for example, reducing a number series by 10%.
Code:
function reduceBy10(&$val, $key) {
$val -= $val * 0.1;
}

$data = array(10,20,30,40);
array_walk($data, 'reduceBy10');
print_r($data);
?>

Output:
Array
(
[0] => 9
[1] => 18
[2] => 27
[3] => 36
)