PHP - Convert a String to Characters With str_split

When passed a string as the only parameter, str_split will convert it into an array of characters.

$charsString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$charsArray = str_split($charsString); // array("a", "b", ....)

This may be useful when creating a character set for a random password generator etc, and will result in a code-base that is faster to write and easier to maintain with a minimal performance penalty.

To demonstrate this, consider the example below and try running it.

<?php

function method1()
{
    $charsString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $charsArray = str_split($charsString);
    return $charsArray;
}

function method2()
{
    $charsArray = array(
        "a","b","c","d","e","f","g","h","i","j","k","l","m",
        "n","o","p","q","r","s","t","u","v","w","x","y","z",
        "A","B","C","D","E","F","G","H","I","J","K","L","M",
        "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
    );

    return $charsArray;
}

$start1 = microtime(true);

for ($i = 0; $i < 1000000; $i++)
{
    method1();
}

$end1 = microtime(true);
print "method1 time taken: " . ($end1 - $start1) . PHP_EOL;

$start2 = microtime(true);

for ($i = 0; $i < 1000000; $i++)
{
    method2();
}

$end2 = microtime(true);
print "method2 time taken: " . ($end2 - $start2) . PHP_EOL;

When running this on my i5-4670K with PHP 7.0, the str_split method resulted in taking 0.96506190299988 seconds, compared to 0.1811740398407 seconds. That may look bad, but don't forget that is for 1 million runs, so a single run or two has an inconsequential impact on performance, especially compared to the look and maintenance of your code-base.

Author

Programster

Stuart is a software developer with a passion for Linux and open source projects.

comments powered by Disqus
We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites. More info.