0

See this code:

<?php

$a = rand(1, 10000000000);
$b = "abcdefghi";

?>

How can I insert $b into a random position of $a?

1
  • 3
    Define "casual position". Do you mean a random position? Commented Jun 7, 2012 at 16:31

5 Answers 5

4

Assuming "casual" means random:

<?php
$a = rand(1, 10000000000);
$b = "abcdefghi";

//get a random position in a
$randPos = rand(0,strlen($a));
//insert $b in $a
$c = substr($a, 0, $randPos).$b.substr($a, $randPos);

var_dump($c);
?>

above code working: http://codepad.org/VCNBAYt1

Edit: had the vars backwards. I read "insert a into b,

Sign up to request clarification or add additional context in comments.

1 Comment

@AldoHolm I read the OP backwards, the original code would insert $a into $b. fixed the code so it does $b into $a.
1

I guess you could by treating $a as a string and concatenating it with $b:

$a = rand(1, 1000000);
$b= "abcd";
$pos = rand(0, strlen($a));
$a =  substr($a, 0, $pos).$b.substr($a, $pos, strlen($a)-$pos);

and the results:

a=525019
pos=4
a=5250abcd19

a=128715
pos=5
a=12871abcd5

Comments

0

You should put {$b} on top of {$a} so that you can insert it to {$b}.. eg:

<?php
   $b = "abcdefghi";
   $a = rand(1, 10000000000);
   $a .= $b;
   echo $a;
?>

2 Comments

what exactly does the order the variables are defined have to do with anything? As long as both variables are defined by the time you use them, order doesn't matter.
Tnks but this isn't random position
0

Sth like this :

<?php
$position = GetRandomPosition();  // you will have to implement this function
if($position >= strlen($a) - 1) {
    $a .= $b; 
} else {
    $str = str_split($a, $position);
    $a = $str[0] . $b . implode(array_diff($str, array($str[0])));
}
?>

Comments

0

Cast $a to string, then use strlen to get the length of $a. Use rand, with with the length of $a as the maximum, to get a random position within $a. Then use substr_replace to insert $b into $a at the position you've just randomized.

Comments

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.