Reputation: 23
i need the functionality of php explode(), but without the separators.
for example, turning the variable "12345" into an array, holding each number seperately.
is this possible? i've already googled but only found explode(), which doesn't seem to work.
thanks!
Upvotes: 2
Views: 4117
Reputation:
with any string in php:
$foo="12345";
echo $foo[0];//1
echo $foo[1];//2
//etc
or (from the preg_split()) page in the manual
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
EVEN BETTER:
$str = 'string';
$chars=str_split($str, 1)
print_r($chars);
benchmark of preg_split() vs str_split()
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$str = '12345';
$time_start = microtime_float();
for ($i = 0; $i <100000; $i++) {
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
//$chars=str_split($str, 1);
}
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "$time seconds\n";
results:
str_split =0.69
preg_split =0.9
Upvotes: 7
Reputation: 57961
Your number can be turned into string and then acted like an array
$i = 2342355; $i=(string)$i;
//or
$i='234523452435234523452452452';
//then
$i[2]==4
//numeration started from 0
Upvotes: 1
Reputation: 5084
If you actually want to create an array, then use str_split(), i.e.,
echo '<pre>'. print_r(str_split("123456", 1), true) .'</pre>';
would result in
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Upvotes: 4