Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP - Convert a String to Characters With str_split

PHP

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.

Last updated: 16th September 2021
First published: 16th August 2018

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch