Search code examples
phparrayswords

Merge 2 array items with same length


i have an array with some words along with it's length which is something like that:

Array
(
    [0] => Array
        (
            [word] => test
            [length] => 4
        )

    [1] => Array
        (
            [word] => sets
            [length] => 4
        )

    [2] => Array
        (
            [word] => foo
            [length] => 3
        )

)

i need to merge array items that have same word length for example the first item has word test which is 4 chars and the second item has word sets which is also 4 chars long so they should be merge like this:

Array
(
        [0] => Array
            (
            [word] => test, sets
            [length] => 4
        )

    [1] => Array
        (
            [word] => foo
            [length] => 3
        )

)

i looked it around stack overflow but couldn't find a solution. if someone has solution here's my code, i really appreciate:

<?php
$words = array();
$length = array();
$words[] = array("word" => "test", "length" => '4');
$words[] = array("word" => "sets", "length" => '4');
$words[] = array("word" => "foo", "length" => '3');
echo '<pre>';
print_r($words);
echo '</pre>';

foreach($words as $key => $test){
    $length[$key] = $test['length'];
    if($test['length']==$length){
        echo 'hello';
    }
}

Solution

  • Ok i just found a solution myself. here's the code for anyone interested finding the solution

    $words = array();
    $words[] = array("word" => "test", "length" => '4');
    $words[] = array("word" => "sets", "length" => '4');
    $words[] = array("word" => "foo", "length" => '3');
    $new_array = array();
    foreach($words as $key => $test){
        $length = $test['length'];
        if(isset($new_array[$length]['word'])){
            $new_array[$length]['word'] = $new_array[$length]['word'].', '.$test['word'];
        }else{
            $new_array[$length]['word'] = $test['word'];
            $new_array[$length]['length'] = $test['length'];
        }
    }
    print_r(array_values($new_array));
    

    and it outputs:

    Array
    (
        [0] => Array
            (
                [word] => test, sets
                [length] => 4
            )
    
        [1] => Array
            (
                [word] => foo
                [length] => 3
            )
    
    )