PHP: insert query result inside array elements [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
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;

Related

how to find minimum difference between average of array and elements in that array in PHP [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 7 years ago.
Improve this question
First of all I need to find average of array, and then I need to find minimum difference between average of array and elements in that array and to display on which place is that element. This is the array:
myArray(4,-18,78,136,-52,14,19,-35,162,71,19,-5,-134,77,-78,-35,19);
You can try this:
<?php
$myArray = array(4,-18,78,136,-52,14,19,-35,162,71,19,-5,-134,77,-78,-35,19);
$averageArray = "";
//Average of the array
if(count($myArray) > 0) {
$averageArray = array_sum($myArray) / count($myArray);
}
$diff = array();
//Diff of average value and each value in a array named diff
if(isset($myArray)) {
foreach($myArray as $value) {
$diff[] = abs($averageArray - $value);
}
}
$key = array_search(min($diff),$diff);
echo "average = " . $averageArray .' - min value :'.min($diff).' - index:'.$key .' value: '.$myArray[$key]."\n";
The first step is to conceptualise an algorithm. What comes to mind is: find the average, find the absolute difference from each element to the average, and then find the minimum. The average can be calculated from the sum and the length.
$avg = array_sum($array) / count($array);
$diff = function ($x) use ($avg) { return abs($x - $avg); };
$answer = min(array_map($diff, $array));
To also get the element that is closest to the average, instead of mapping to just the difference we can keep the original element along for the ride. Then when we find the minimum we only compare the difference.
function minBy(callable $f, array $xs) {
$min = $xs[0];
foreach ($xs as $x) {
if ($f($x, $min) < 0) $min = $x;
}
return $min;
}
$avg = array_sum($array) / count($array);
$diff = function ($x) use ($avg) { return array($x, abs($x - $avg)); };
$byDiff = function ($x,$y) { return $x[1] - $y[1]; };
$answer = minBy($byDiff, array_map($diff, $array));
To find the index of the element in the array (note that this may not be unique), you can use array_search.
Crude but working:
<?php
$myArray = [4,-18,78,136,-52,14,19,-35,162,71,19,-5,-134,77,-78,-35,19];
// the average: sum/count
$average = round(array_sum($myArray) / count($myArray));
foreach ($myArray as $value) {
$diffs[] = abs($average - $value);
}
asort($diffs);
print_r($diffs);
$d = reset($diffs);
$p = array_search($d, $diffs);
echo sprintf("Average: %s, min diff: %s, diff pos: %s\n", $average, $d, $p);

PHP code is returning "x=NAN" [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
My code is:
$a = $_GET["valA"];
$b = $_GET["valB"];
$c = $_GET["valC"];
$d = pow($b,2) - 4 * $a * $c;
$e = sqrt($d);
$f = $e - $b;
$g = 2 * $a;
$h = $f / $g;
echo "x = $h";
And it is returning:
x = NAN
Please point out my mistake.
Issue is with $e = sqrt($d);
Whenever $d gives a NEGATIVE value sqrt($d) returns NAN.
EXAMPLE
echo $e = sqrt(-4);
returns NAN
AND
echo $e = sqrt(4);
returns 2
NAN simply means Not A Number. The values you are pulling from the URL may be strings, which would cause this issue.
Also I think the problem may occur if you are taking the square root of a negative number.
You could use something like this to solve it
<?php
$a = 10;
$b = 20;
$c = 30;
$d = pow($b,2) - 4 * $a * $c;
if($d < 0){
$d *= -1;
}
$e = sqrt($d);
$f = $e - $b;
$g = 2 * $a;
$h = $f / $g;
?>

What's wrong with mt_rand in PHP? [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
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

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);

How to sum a set of values from a form in PHP? [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 9 years ago.
Improve this question
I have a simple form and a submit button. After pressing the submit button, get the values (they will be numbers) and calculate the sum. And again calculate the sum of individual digits stored in sum.
A better explanation: 1+2+3+4=10 where 1,2,3 and 4 are user inputs from the form. And the sum 10 has to be split-ted and summed again as 1+0=1. And this would be my final result. So far I did the task where it gives me the first sum. I don't know what to do to display the second result which I want to be the finale.
<?php
$a='';
$sum='';
$total='';
if (!isset($_POST['submit'])) {
echo " ";
}
else {
$a = array($_POST['textfield'],$_POST['textfield1'],$_POST['textfield2'],$_POST['textfield3'],$_POST['textfield4'],$_POST['textfield5'],$_POST['textfield6'],$_POST['textfield7'],$_POST['textfield8'],$_POST['textfield9'],$_POST['textfield10'],$_POST['textfield11'],);
for ($i=0; $i<=12; $i++) {
$sum= array_sum($a);
$total= ;
}
}
echo "sbora e: $total ";
?>
$total = array_sum(str_split($sum));
Using Artefacto's method.
On another note,
$a = array($_POST['textfield'],$_POST['textfield1'],$_POST['textfield2'],$_POST['textfield3'],$_POST['textfield4'],$_POST['textfield5'],$_POST['textfield6'],$_POST['textfield7'],$_POST['textfield8'],$_POST['textfield9'],$_POST['textfield10'],$_POST['textfield11'],);
can be written as,
$a = array();
for ($i = 0; $i <= 11; $i++){
if (isset($_POST["textfield_$i"]))
array_push($a, $_POST["textfield_$i"]);
}
if the names of the fields are:
textfield_0, textfield_1, textfield_2...
So you want to build the cross sum of your first result:
$result2 = 0;
//cast integer to string
$strTotal = (string) $total;
//loop over "chars" and add them to your second result
for($i=0; $i < strlen($strTotal); $i++)
{
$result2 += $strTotal{$i};
}

Categories