1

I have a form with a textarea and a submit button. What I'd like to do is add one word per line in the text area and when the form is submitted I'd like to go through each word, join it randomly with another.

So for example if I submit this:

word1
word2
word3
word4

the result could be something like this:

word3word4
word1word2
word4word1
etc.

So far I have the form:

<form action="index.php" method="POST">

    <textarea rows="5" name="strings" id="strings"></textarea><br /><br />
    <input type="submit" value="submit">

</form>

I store use submission in a variable like this:

$strings = $_POST['strings'];
$stringsArray = explode("\n", $strings);

I was thinking using the foreach loop but I'm not sure how to display only 2 words per iteration.

Xorifelse
  • 7,878
  • 1
  • 27
  • 38
PapT
  • 603
  • 4
  • 14
  • 30

2 Answers2

2

I think you are looking for the cartesian product of two arrays: Please refer to: PHP 2D Array output all combinations

Where your first array and second array are $stringsArray. From the valid answer in the given link you should use:

function array_cartesian() {
    $_ = func_get_args();
    if(count($_) == 0)
        return array(array());
    $a = array_shift($_);
    $c = call_user_func_array(__FUNCTION__, $_);
    $r = array();
    foreach($a as $v)
        foreach($c as $p)
            $r[] = array_merge(array($v), $p);
    return $r;
}
$words = array('word1', 'word2',  'word3');
$cross = array_cartesian($words,$words);

Then you can use this to display the result:

foreach($cross as $item){
    if($item[0] != $item[1]) print($item[0].$item[1]."\n");
 }
Community
  • 1
  • 1
Jefferson Javier
  • 317
  • 2
  • 10
1

Because you want random values you cannot loop with foreach because it loops in order.

Instead use a for loop:

$stringArray = ['word1', 'word2', 'word3', 'word4'];

for($i = 0, $c = count($stringArray); $i < $c; $i++){
    $lines[] = $stringArray[rand(0, $c - 1)] . $stringArray[rand(0, $c - 1)];
}

print_r($lines);

However, this will be completely random and it can concat the same string twice but you didn't exclude that option either.

Xorifelse
  • 7,878
  • 1
  • 27
  • 38