As you may know, in the C language a string is in fact an array of characters, terminated by the null character \0.
In PHP, the idea is still here but it’s a little bit different. Strings are not considered as array but each characters are easily reachable using the following syntax :
$str = 'Hello World!';
$char = $str{4};
echo $char; // output : o
So, you may iterate on string characters to build an array :
$str = 'Hello World!';
$n = strlen($str);
$arr = array();
for ($i = 0; $i < $n; $i++){
$arr[$i] = $str{$i};
}
But, it’s by far not the easiest way to convert a string into an array
PHP has already a built-in function to do the job : str_split.
$str = 'Hello World!';
$arr = str_split($str);
print_r($arr);
/*
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => W
[7] => o
[8] => r
[9] => l
[10] => d
[11] => !
)
*/
Plus, str_split has another cool feature : if the optional second parameter is specified, the returned array will be broken down into chunks with each the length you have chosen.
$str = 'Hello World!';
$arr = str_split($str, 2);
print_r($arr);
/*
Array
(
[0] => He
[1] => ll
[2] => o
[3] => Wo
[4] => rl
[5] => d!
)
*/
Now, let’s make an example with a very simple string to hexadecimal representation function :
function str_to_hex($str)
{
$n = strlen($str);
$str = str_split($str);
for ($i = 0; $i < $n; $i++){
$str[$i] = dechex(ord($str[$i]));
}
return implode($str);
}
echo str_to_hex('Hello'); // output : 48656c6c6f
The reverse :
function hex_to_str($str)
{
$str = str_split($str, 2);
$n = sizeof($str);
for ($i = 0; $i < $n; $i++){
$str[$i] = chr(hexdec($str[$i]));
}
return implode($str);
}
echo hex_to_str('48656c6c6f'); // output : Hello
Enjoy
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
Hello,
Good article
Be careful if you use this function in a multi-byte encoding (like UTF-8). Indeed, str_split cut on the number of bytes, not the number of characters.