Home » Php » PHP: Split a string in to an array foreach char

PHP: Split a string in to an array foreach char

Posted by: admin April 23, 2020 Leave a comment


I am making a method so your password needs at least one captial and one symbol or number.
I was thinking of splitting the string in to lose chars and then use preggmatch to count if it contains one capital and symbol/number.

however i did something like this in action script but can’t figure out how this is called in php. i cant find a way to put every char of a word in a array.

AS3 example

    for(var i:uint = 0; i < thisWordCode.length -1 ; i++)
    thisWordCodeVerdeeld[i] = thisWordCode.charAt(i);
    //trace (thisWordCodeVerdeeld[i]);


How to&Answers:

You can access characters in strings in the same way as you would access an array index, e.g.

$length = strlen($string);
$thisWordCodeVerdeeld = array();
for ($i=0; $i<$length; $i++) {
    $thisWordCodeVerdeeld[$i] = $string[$i];

You could also do:

$thisWordCodeVerdeeld = str_split($string);

However you might find it is easier to validate the string as a whole string, e.g. using regular expressions.


you can convert a string to array with str_split and use foreach

$chars = str_split($str);
foreach($chars as $char){
    // your code


You can access a string using [], as you do for arrays:

$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
    $char = $str[$i];


Since str_split() function is not multibyte safe, an easy solution to split UTF-8 encoded string is to use preg_split() with u (PCRE_UTF8) modifier.

preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )


A less readable, but better performing solution, when iterating over many strings, might be using isset to check the end of the string. This might be better performing because isset is a language construct and strlen is a function:

for ($i = 0; isset($value[$i]); $i++) {
    "do something here"

This question should provide more background.