1

I want to suggest possible words to my clients like this :

t.est te.st tes.t te.st tes.t t.e.s.t

Now my code would be ?

<?php 

$string = "test";
$array = str_split($string);

foreach($array as $letter){
    echo $letter.".";
}
4
  • php.net/array_shuffle and then some conditional logic/looping to "sprinkle" the . throughout the shuffled characters. Commented Apr 4, 2014 at 16:44
  • It doesn't seem like he wants to shuffle the characters though? All of his examples had them in order... Commented Apr 4, 2014 at 16:49
  • I have a really convoluted method in my head that is probably far from the best but... here goes. You get the character count of your string (let's call it x) and then do 2^x-1 to get the amount of permutations you will need (let's call it y.) For instance, a 3 character string would be 2^2 or 4 permutations... dog, d.og, do.g, d.o.g (make sense so far?) Then you do a z=0 while z<y loop... so if our y is 4 we will loop through the ints 0, 1, 2, and 3. (More in next comment...) Commented Apr 4, 2014 at 16:58
  • Ok so then within the loop you convert your integers to binary... so in this example you will loop through 00, 01, 10, 11. And... that binary basically tells you whether you put a dot after a character or not. 00 = dog, 01 = do.g, 10 = d.og, 11 = d.o.g so... yeah. This will work, it's just uber convoluted. Commented Apr 4, 2014 at 17:00

1 Answer 1

2

I hope this is solves your problem:

$string = "test";
$array = str_split($string);


$len = strlen($string);    
$rand_indx = mt_rand(0,$len);


if ($rand_indx == $len) {
    $array[$rand_indx] = ".";
} else {
    for ($x=$len; $x > $rand_indx; $x--) {
        $array[$x] = $array[$x-1];
    }
    $array[$rand_indx] = ".";
}

foreach($array as $letter){

    echo $letter;
}
Sign up to request clarification or add additional context in comments.

2 Comments

The 4s should probably be strlen($string) to make it work with any string.
Absolutely... That would definitely give it more flexibility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.