Home > Enterprise >  PHP, from string to array by length of words
PHP, from string to array by length of words

Time:09-02

how i can transform a string in an array?, example:

$string = "hi my name is Joe";

result:

$array = [
"2" => ["hi", "my", "is"],
"4" => ["name"],
"3" => ["Joe"]
];

where "2" rapresent the number of characters.

initially I created an array formed by the words present in the string:

function ordina3($string) {
        $array = explode(" ", $string);

        $tmpArray= [];
        
        for ($i=0; $i < count($array); $i  ) { 
            $length = strlen($array[$i]);
   
            if (!in_array($length, $tmpArray)){
                array_push($tmpArray, $length);
            }
        return $tmpArray;
}

but I don't know how to continue

CodePudding user response:

The following code will help you to get the result:
    $string = "hi my name is Joe";
    $arrayString = explode(" ", $string);
    $result = array();
    foreach ($arrayString as $item) {
        $result [strlen($item)][] = $item;
    }
    echo $result;

CodePudding user response:

   
$string = "hi my name is Joe";
$StringArray = explode(" ", $string);
$resultarr = array();
foreach ($StringArray as $item) 
{
    $resultarr[strlen($item)][] = $item;
}
echo '<pre>'; 
print_r($resultarr);

  • Related