What's wrong with mt_rand in PHP? [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I tried to make a simple name generator. Help me to identify why it's not working. I think it's because of mt_rand function. Sorry if question seems banal or irrelevant, I'm first time here and new to programming. Here's the code:
<?php
echo 'Ovo je moja verzija Polumenta generatora';
$prvo = 'bcdfghtnjpknmlrjdzdjs';
$drugo = 'aeiou';
$trece = 'bcdfghtnjpknmlrjsdzdj';
$cetvrto = 'uo';
$prvos = mt_rand($prvo[0],$prvo[17]);
$drugos = mt_rand($drugo[0],$drugo[4]);
$treces = mt_rand($trece[0],$trece[17]);
$cetvrtos = mt_rand($cetvrto[0],$cetvrto[1]);
echo $prvos.$drugos.$treces.$cetvrtos.' Polumenta'
?>

mt_rand takes integers as arguments and returns an integer. You are trying to pass it characters and return characters. You should do something like:
<?php
echo 'Ovo je moja verzija Polumenta generatora';
$prvo = 'bcdfghtnjpknmlrjdzdjs';
$drugo = 'aeiou';
$trece = 'bcdfghtnjpknmlrjsdzdj';
$cetvrto = 'uo';
$prvos = $prvo[mt_rand(0,strlen($prvo) - 1)];
$drugos = $drugo[mt_rand(0,strlen($drugo) - 1)];
$treces = $trece[mt_rand(0,strlen($trece) - 1)];
$cetvrtos = $cetvrto[mt_rand(0,strlen($cetvrto) - 1)];
echo $prvos.$drugos.$treces.$cetvrtos.' Polumenta'
?>

You can make it in another way, using arrays and rand() function.
$chrs[0] = str_split('bcdfghtnjpknmlrjdzdjs'); // array of consonants
$chrs[1] = str_split('aeiou'); // array of vowels
$length = 8; // nick name length
Than generate random sequence of chars any length
for($i = 0; $i < $length; $i++)
{
$v_or_c = rand(0,1);
if($v_or_c)
{
$nick_name .= $chrs[$v_or_c][rand(0, sizeof($chrs[$v_or_c]))];
}
else
{
$nick_name .= $chrs[$v_or_c][rand(0, sizeof($chrs[$v_or_c]))];
}
}
echo ucfirst($nick_name); // ucfirst - to upper case first letter

Related

PHP: insert query result inside array elements [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
function standard_deviation_population ($a)
{
//variable and initializations
$the_standard_deviation = 0.0;
$the_variance = 0.0;
$the_mean = 0.0;
$the_array_sum = array_sum($a); //sum the elements
$number_elements = count($a); //count the number of elements
//calculate the mean
$the_mean = $the_array_sum / $number_elements;
//calculate the variance
for ($i = 0; $i < $number_elements; $i++)
{
//sum the array
$the_variance = $the_variance + ($a[$i] - $the_mean) * ($a[$i] - $the_mean);
}
$the_variance = $the_variance / $number_elements;
//calculate the standard deviation
$the_standard_deviation = pow( $the_variance, 0.5);
//return the variance
return $the_standard_deviation;
}
$query_question = mysqli_query($con,"SELECT * FROM question order by s_id");
$QuestionDimArray = array();
while ($data_question = mysqli_fetch_array($query_question))
{
$QuestionDimArray []= $data_question['q_id'];
}
$a = array($QuestionDimArray());
$standard_deviation = standard_deviation_population ($a);
echo "standard_deviation =" .$standard_deviation;
How to store database value into
$variable = array([database values here]);
for example, with defined values (1,2,3)
$a = array(1,2,3);
$standard_deviation = standard_deviation_population ($a);
echo "standard_deviation =" .$standard_deviation;
that returns,
standard_deviation = 0.81649658092773
It is not good idea to calculate the standard deviation this way. Database systems has a built-in functions for standard deviation. You can get it in one query, something like this: SELECT STDDEV_POP(q_id) FROM question.
In your code the $QuestionDimArray is already an array. You could just $standard_deviation = standard_deviation_population ($QuestionDimArray);
Your question is not clear but if I understand well you want put all your database result in $variable ?
$query_question = mysqli_query($con,"SELECT * FROM question order by s_id");
$QuestionDimArray = array();
while ($data_question = mysqli_fetch_array($query_question)) {
$QuestionDimArray []= $data_question['q_id'];
/* if you want the full data line from your query use. It depends your implementation.
You will have an 2d array
[['col1' => 'val_line_1_1', 'col2'=> 'val_line_1_2',...],...,['col1' => 'val_line_n_1', 'col2'=> 'val_line_n_2',...]]
$QuestionDimArray []= $data_question;
*/
}
// $a = array($QuestionDimArray()); unless you want copy the array this line is useless. Event worst its wrong
$standard_deviation = standard_deviation_population ($questionDimArray);
echo "standard_deviation =" .$standard_deviation;

How To Display Random Results in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Im trying to display 2 or more unique random results from a text file, How do I do that please?
But I need unique results and not 2 or more of the same.
Currently using this code, but it only returns 1 random result:
<?php
$text = file_get_contents('flatFileDB.txt');
$textArray = explode("\n", $text);
$randArrayIndexNum = array_rand($textArray);
$randPhrase = $textArray[$randArrayIndexNum];
?>
<?php echo $randPhrase ?>
I would use something like that
shuffle($textArray);
echo $textArray[0];
echo $textArray[1];
http://php.net/manual/tr/function.shuffle.php
You can give a shot to this also. Code is not tested. I am collecting the used into an array, and check, is that used before.
$text = file_get_contents('flatFileDB.txt');
$textArray = explode("\n", $text);
$used = array();
$countOfRandoms = 2;
$randoms = array();
$i = 1;
do {
if ($countOfRandoms == $i) {
break;
}
$randArrayIndexNum = array_rand($textArray);
if (in_array($randArrayIndexNum, $used)) {
continue;
}
$used[] = $randArrayIndexNum;
$random = $textArray[$randArrayIndexNum];
$i++;
} while (true);

PHP function to get N random values (as array) which's sum result in X [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I think the subject hits it better than I was expecting.
I need a function which returns random numbers which result in a given value (X) when they are summed up.
Something like this:
getRandomTo(10); // result for example: array(2,3,5)
getRandomTo(10); // result for example: array(4,3,3)
getRandomTo(12); // result for example: array(5,1,6)
I could not find a generic algorithm function for solving that requirement. Further more I cannot imagine a FAST and performant way to create something like this my self.
Please help me out
function getRandomTo($num)
{
$x = Array();
$i = 0;
do
{
$x[$i] = rand(1,$num);
$num = $num - $x[$i];
$i++;
}while($num > 0);
print_r($x);
}
Maybe do this:
create a random value between 0 and X; say this one is called r1. save this in your array.
create another random value between 0 and (X-r1), name it r2. save it also.
do these steps as often as you need it (or as long as r1+...+rn is lower than X)
Another solution:
function randomTo($numIn) {
$numOut = 0;
$numbers = array();
do {
$add = rand(1, $numIn);
if($numOut + $add > $numIn)
continue;
$numOut += $add;
$numbers[] = $add;
} while( $numOut != $numIn );
return $numbers;
}
$result = randomTo(15);
var_dump($result);

Looking for improvement on PHP split and combination function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Suppose I have a string such as this:
ABC.DEF.GHI.JKL (This string could have any length and amount of characters between dots)
I want to add the following combinations into an array.
ABC
ABC.DEF
ABC.DEF.GHI
ABC.DEF.GHI.JKL
So basically the string should be split with the dot character and then the individual sub-strings should be combined.
I have a function already, but in my opinion this seems too complicated to achieve the result.
$myarray = array();
$split = explode('.', 'that.string.with.dots');
$string = '';
for ($i = 0; $i < count($split); $i++) {
$string .= $split[$i];
myarray[] = $string;
$string .= '.';
}
Any suggestions on improving this?
Thanks
Michael
Perhaps this:
$split = explode('.', 'that.string.with.dots');
for ($i = 1; $i < count($split); $i++) {
$split[i] = $split[$i-1] . '.' . $split[i];
}
It just concats the current with the previous.
I have the feeling that you are asking if there is a PHP function that will achieve this result with a single function call, but I don't think there is one.
You can rewrite the code as pritaeas did in his answer, to remove two lines of code, but it will still be the same concept.

Fast way to generate token - PHP [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP: How to generate a random, unique, alphanumeric string?
i want to generate random token [alphanumeric] for random length [between 4-6] characters.
Can anyone help ?
You could use uniqid (search for "token" in the examples given there) and shorten it with substr.
Firstly, you can just get a random number between 10+26+26=62 6 times, and then calculate the resulted string, this seems easy enough.
<?php
function ()
{
$letters={a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9,10}
return array_rand($letters).array_rand($letters)......... // you get the point
?>
or if you prefer the 'hard' way...
$len = random(4,6);
$token = array();
for ($i = 0; $i < $len; $i++) {
$ord = 0;
switch(random(1,3)) {
case 1: // 0 - 9
$ord = random(48,57);
break;
case 2: // A - Z
$ord = random(65,90);
break;
case 3: // a - z
$ord = random(97,112);
break;
}
$token[] = chr($ord);
}

Categories