Search code examples
phptexttextcolor

array_rand wihout repeating in php


I'm working with my code that will allow the user to input a word and each letter of the word will give a meaning.

Example: User inputted a text "APPLE". Output:

A - arc
P - priest
P - president
L - lion
E - escape

The meaning of every letter will be in array..

I already have my code here but the meaning are repeated.

Example:

A -  **Arrow**
L -  Love
A - **Arrow**
S - Soul

Here's my code

<?php
$chars = str_split("APPLE");
foreach($chars as $char){
    if (substr($char, 0, 1) === 'A')
    {
    $meaning = array("Angel","Ancient","Arrow");
    echo $meaning[array_rand($meaning)];
    }
}
?>

Solution

  • You could unset it temporarily inside the loop so that you won't get dups. Example:

    $chars = str_split("APPLE");
    $words = array(
        // its up to you what words you want to map
        'A' => array("Angel","Ancient","Arrow"),
        'E' => array('Elephat', 'Eardrum'),
        'L' => array('Level', 'Laravel', 'Love'),
        'S' => array('Sweet', 'Spicy', 'Savy'),
        'P' => array('Powerful', 'Predictable', 'Pass', 'piss')
    );
    
    foreach($chars as $char){
        $random_key = array_rand($words[$char]); // get random key
        $key = $words[$char][$random_key]; // get the word
        unset($words[$char][$random_key]); // unset it so that it will never be repeated
        echo "$char - $key <br/>";
    }