Skip to content
Advertisement

PHP swapping elements between 2 tables

$tab1 = [“echelle”, “trio”, “pamplemousse”, “legumes”];

$tab2 = [“lama”, “geranium”, “pendule”, “elephant”];

Question: Sort the 2 tables in such a way that table 1 contains only words that have at least 1 time the letter “u” and the second table the rest of the words that do not.

Hello, i’m a bit lost on displaying my code. I got the idea, which is adding elements that contains the letter ‘u’ to the 1st table, and deleting elements that doesn’t contain the letter, and vice versa for the 2nd table, but i’m not sure how to do it.

i considered swapping elements, not sure if that would work:

for ($i=$position; $i < $tableau1[$position]; $i++) { 

    if (substr($tableau1 , $i , 1) == "u") {
        $temporaire = $tableau1[$position];
        $tableau1[$position] = $tableau2[$position];
        $tableau2[$position] = $temporaire;

    }   
}

maybe this way:

while ($tableau1[$position]) {
    
    if (substr($tableau1 , $i , 1) == "u") {
        array_push($tableau2, $tableau1[$position]);
    }
    $position++;
}

Advertisement

Answer

Merge the two arrays together then sort everything into the groups you want.

$tab1 = ["echelle", "trio", "pamplemousse", "legumes"];

$tab2 = ["lama", "geranium", "pendule", "elephant"];

// Merge the two arrays into one so we can look at each word in turn
$tab3 = array_merge( $tab1, $tab2 );

// Create new empty arrays so we can add the words into the right place
$tab1 = array();
$tab2 = array();

foreach ( $tab3 as $word ) {
    if ( strpos( $word, 'u' ) !== FALSE ) {
        $tab1[] = $word; // Words with a 'u' go in table 1
    } else {
        $tab2[] = $word; // Words without a 'u' go in table 2
    }
}

print_r( $tab1 );
print_r( $tab2 );

Result:

Array
(
    [0] => pamplemousse
    [1] => legumes
    [2] => geranium
    [3] => pendule
)
Array
(
    [0] => echelle
    [1] => trio
    [2] => lama
    [3] => elephant
)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement