Reduce php if statements - php

Is there a way to reduce this if statements? I got a bit in trouble, because the var ($c1g, $c2g aso.) also changes in every if statement.
$c1 = $_POST['category_1'];
if($c1=='perfect')
{
$c1g = $perfect[1];
}
else if($c1=='good')
{
$c1g = $good[1];
}
else {
$c1g = $bad[1];
}
$c2 = $_POST['category_2'];
if($c2=='perfect')
{
$c2g = $perfect[1];
}
else if($c2=='good')
{
$c2g = $good[1];
}
else {
$c2g = $bad[1];
}
...

It still kind of smells, but if you had an array indexed on the perfect, good, bad:
$values = ['perfect' => [1=>1, 2=>2, 3=>3],
'good' => [1=>1, 2=>2, 3=>3],
'bad' => [1=>1, 2=>2, 3=>3]];
Then you could use the posted value:
$c1 = $_POST['category_1'];
$c1g = $values[$c1][1] ?? $values['bad'][1];
$c2 = $_POST['category_2'];
$c2g = $values[$c2][1] ?? $values['bad'][1];
And if your posted values were grouped in another dimension like $_POST['cats']['category_2'] then you could just loop over $_POST['cats'].

Related

Set the value of a variable based on the value of another variable php

New to programming and looking for help please,
i need to the set the value of $b_num based on the value of $egg_type i have tried using an if statement but not having any luck
`
$egg_type = $row["egg_type"] ;
if ($egg_type == 'M/S Select Farm')
{
$b_num = '1';
}
if ($egg_type = 'Free Range')
{
$b_num = '1';
}
if ($egg_type = 'Barn')
{
$b_num = '2';
}
if ($egg_type =='Intensive')
{
$b_num = '3';
}
if ($egg_type == 'Organic')
{
$b_num = '0';
}
if ($egg_type == 'Brioche')
{
$b_num = '3';
}
`
Tried the if statement but the value didnt change,
First you've to check if your $egg_type variable is being set in order not to make errors later
Second you can do it like this
if(isset($egg_type)) {
if(in_array($egg_type, ['M/S Select Farm', 'Free Range'])) {
$b_num = 1;
} elseif(in_array($egg_type, ['Intensive', 'Brioche'])) {
$b_num = 3;
} elseif($egg_type === 'Organic') {
$b_num = 0;
} elseif($egg_type === 'Barn') {
$b_num = 2;
}
}
Maybe $egg_type is null value. Therefore,you can improve your code (PHP 8.0 version) and set default value for b_num like this:
$egg_type = $row["egg_type"] ;
$b_num = match($egg_type) {
'M/S Select Farm' => 1,
'Free Range' => 1,
'Barn' => 1,
'Intensive' => 1,
'Organic' => 1,
'Brioche' => 1,
default => 'nothing any value for b_num'
};
echo $b_num;

How to make dynamic array from static array

I have trouble with my static array, i need to update with dynamic array can someone help me ? because will be so hard if i have alot data and i must create 1 by 1.
$kriteria = [C1,C2,C3,C4,C5,C6];
$alternatif = [ALT1,ALT2,ALT,ALT4,ALT5,ALT6,ALT7];
$nEntropy = array();
for ($i=0;$i<count($kriteria);$i++)
{
for ($j=0;$j<count($alternatif);$j++)
{
$nEntropy[$i] = (((-1)/log(7)) *(
($probabilitas[0][0]*log($probabilitas[0][0]))+
($probabilitas[1][0]*log($probabilitas[1][0]))+
($probabilitas[2][0]*log($probabilitas[2][0]))+
($probabilitas[3][0]*log($probabilitas[3][0]))+
($probabilitas[4][0]*log($probabilitas[4][0]))+
($probabilitas[5][0]*log($probabilitas[5][0]))+
($probabilitas[6][0]*log($probabilitas[6][0]))
));
}
}
$nEntropy1 = array();
for ($i=0;$i<count($kriteria);$i++)
{
for ($j=0;$j<count($alternatif);$j++)
{
$nEntropy1[$i] = (((-1)/log(7)) *(
($probabilitas[0][1]*log($probabilitas[0][1]))+
($probabilitas[1][1]*log($probabilitas[1][1]))+
($probabilitas[2][1]*log($probabilitas[2][1]))+
($probabilitas[3][1]*log($probabilitas[3][1]))+
($probabilitas[4][1]*log($probabilitas[4][1]))+
($probabilitas[5][1]*log($probabilitas[5][1]))+
($probabilitas[6][1]*log($probabilitas[6][1]))
));
}
}
$nEntropy2 = array();
for ($i=0;$i<count($kriteria);$i++)
{
for ($j=0;$j<count($alternatif);$j++)
{
$nEntropy2[$i] = (((-1)/log(7)) *(
($probabilitas[0][2]*log($probabilitas[0][2]))+
($probabilitas[1][2]*log($probabilitas[1][2]))+
($probabilitas[2][2]*log($probabilitas[2][2]))+
($probabilitas[3][2]*log($probabilitas[3][2]))+
($probabilitas[4][2]*log($probabilitas[4][2]))+
($probabilitas[5][2]*log($probabilitas[5][2]))+
($probabilitas[6][2]*log($probabilitas[6][2]))
));
}
}
$nEntropy3 = array();
for ($i=0;$i<count($kriteria);$i++)
{
for ($j=0;$j<count($alternatif);$j++)
{
$nEntropy3[$i] = (((-1)/log(7)) *(
($probabilitas[0][3]*log($probabilitas[0][3]))+
($probabilitas[1][3]*log($probabilitas[1][3]))+
($probabilitas[2][3]*log($probabilitas[2][3]))+
($probabilitas[3][3]*log($probabilitas[3][3]))+
($probabilitas[4][3]*log($probabilitas[4][3]))+
($probabilitas[5][3]*log($probabilitas[5][3]))+
($probabilitas[6][3]*log($probabilitas[6][3]))
));
}
}
$nEntropyy4 = array();
for ($i=0;$i<count($kriteria);$i++)
{
for ($j=0;$j<count($alternatif);$j++)
{
$nEntropy4[$i] = (((-1)/log(7)) *(
($probabilitas[0][4]*log($probabilitas[0][4]))+
($probabilitas[1][4]*log($probabilitas[1][4]))+
($probabilitas[2][4]*log($probabilitas[2][4]))+
($probabilitas[3][4]*log($probabilitas[3][4]))+
($probabilitas[4][4]*log($probabilitas[4][4]))+
($probabilitas[5][4]*log($probabilitas[5][4]))+
($probabilitas[6][4]*log($probabilitas[6][4]))
));
}
}
$nEntropy5 = array();
for ($i=0;$i<count($kriteria);$i++)
{
for ($j=0;$j<count($alternatif);$j++)
{
$nEntropy5[$i] = (((-1)/log(7)) *(
($probabilitas[0][5]*log($probabilitas[0][5]))+
($probabilitas[1][5]*log($probabilitas[1][5]))+
($probabilitas[2][5]*log($probabilitas[2][5]))+
($probabilitas[3][5]*log($probabilitas[3][5]))+
($probabilitas[4][5]*log($probabilitas[4][5]))+
($probabilitas[5][5]*log($probabilitas[5][5]))+
($probabilitas[6][5]*log($probabilitas[6][5]))
));
}
}
showb($nEntropy);
showb($nEntropy1);
showb($nEntropy2);
showb($nEntropy3);
showb($nEntropy4);
showb($nEntropy5);
this image for my results
as you can see my code really static and so hard if i have alot data
and also i need my results likes this
EDIT
the answers from Vörös Amadea are correct, but there are still some that are lacking, my second question regarding the results is still in large numbers. is there a way to display it only once?
as u can see on my image before, i need to remove duplicate data so only 1 for each is who will displayed and store it into array.
I have modified a little code from Vörös Amadea because if I don't modify it, I get an error "Undefined variable: probability"
this is the code that I have modified.
for($x=0;$x<1;$x++){
$nth = $x;
$entz = array();
for ($i=0;$i<count($kriteria);$i++)
{
for ($j=0;$j<count($alternatif);$j++)
{
${"entz$nth"}[$i] = (((-1)/log(7)) *(
($probabilitas[0][$nth]*log($probabilitas[0][$nth]))+
($probabilitas[1][$nth]*log($probabilitas[1][$nth]))+
($probabilitas[2][$nth]*log($probabilitas[2][$nth]))+
($probabilitas[3][$nth]*log($probabilitas[3][$nth]))+
($probabilitas[4][$nth]*log($probabilitas[4][$nth]))+
($probabilitas[5][$nth]*log($probabilitas[5][$nth]))+
($probabilitas[6][$nth]*log($probabilitas[6][$nth]))
));
}
}
}
showb(${"entz$nth"});
You can generate variable names in for loops like this.
Just change the value of $how_many_i_want.
$how_many_i_want = 3;
for($x=0;$x<$how_many_i_want;$x++){
generate_entropy($x);
}
function generate_entropy($nth){
$kriteria = ['C1','C2','C3','C4','C5','C6'];
$alternatif = ['ALT1','ALT2','ALT','ALT4','ALT5','ALT6','ALT7'];
${"nEntropy$nth"} = array();
for ($i=0;$i<count($kriteria);$i++){
for ($j=0;$j<count($alternatif);$j++){
${"nEntropy$nth"}[$i] = (((-1)/log(7)) *(
($probabilitas[0][$nth]*log($probabilitas[0][$nth]))+
($probabilitas[1][$nth]*log($probabilitas[1][$nth]))+
($probabilitas[2][$nth]*log($probabilitas[2][$nth]))+
($probabilitas[3][$nth]*log($probabilitas[3][$nth]))+
($probabilitas[4][$nth]*log($probabilitas[4][$nth]))+
($probabilitas[5][$nth]*log($probabilitas[5][$nth]))+
($probabilitas[6][$nth]*log($probabilitas[6][$nth]))
));
}
}
showb(${"nEntropy$nth"});
}

Catch Tweets with JSON and sort by likes?

I am currently running a wordpress backend and want to display some tweets based on hastags on my website. For the general API request and database storage, I use this function:
private function parseRequest($json) {
$tmp = $json;
$result = array();
if (isset($json['statuses'])) {
$tmp = $json['statuses'];
}
if (isset($tmp) && is_array($tmp)){
foreach ($tmp as $t) {
$this->image = null;
$this->media = null;
$tc = new \stdClass();
$tc->feed_id = $this->id();
$tc->id = $t['id_str'];
$tc->type = $this->getType();
$tc->nickname = '#'.$t['user']['screen_name'];
$tc->screenname = (string)$t['user']['name'];
$tc->userpic = str_replace('.jpg', '_200x200.jpg', str_replace('_normal', '', (string)$t['user']['profile_image_url']));
$tc->system_timestamp = strtotime($t['created_at']);
$tc->text = $this->getText($t);
$tc->userlink = 'https://twitter.com/'.$t['user']['screen_name'];
$tc->permalink = $tc->userlink . '/status/' . $tc->id;
$tc->media = $this->getMedia($t);
#$tc->additional = array('shares' => (string)$t['retweet_count'], 'likes' => (string)$t['favorite_count'], 'comments' => (string)$t['reply_count']);
if ($this->isSuitablePost($tc)) $result[$tc->id] = $tc;
}
}
return $result;
}
Now I am looking for a function that counts all the variable in the "additional array together e.g. shares + likes + comments and sorts all posts based on the resulting number.
I am using the standard wordpress sql database. I cannot find a solution or I am just blind.
Thanks in regards
You could use a simple usort function:
usort($tc, function($a, $b) {
$a_sum = array_sum($a->additional);
$b_sum = array_sum($b->additional);
if ($a_sum == $b_sum) {
return 0;
}
return ($a_sum < $b_sum) ? -1 : 1;
});

Prevent insert query with php

I have a php which will include my datas inside my database.
But in my page I have a div which can be replicated, so I send this informations into an array (imploded with a "#!#" to avoid any kind of wrong explode when I insert it on my database).
My problem is that if the user doesn't insert anything on the first div content fields I shall not do the insert, and it still does.
if ($_GET['action_ent'] != "#!##!##!#")
{
$myInputs = $_GET['action_ent'];
foreach ($myInputs as $eachInput)
{
$valores = $eachInput;
print_r($valores);
$dummy = explode('#!#', $valores);
$acao = $dummy[0];
$resp_acao = $dummy[1];
$inic_plan_acao = $dummy[2];
$fim_plan_acao = $dummy[3];
$inicio_acc = explode("/", $inic_plan_acao);
$fim_acc = explode("/", $fim_plan_acao);
$inicio_action = $inicio_acc[2]."-".$inicio_acc[1]."-".$inicio_acc[0];
$fim_action = $fim_acc[2]."-".$fim_acc[1]."-".$fim_acc[0];
$result2 = mysql_query("INSERT INTO `demv3`.`entraves_action` (`action_id`, `ent_id`, `resp_ent`, `data_fim`,`action_desc`,`action_resp`,`action_comeco`,`action_fim`) VALUES ('0', '$ent_id', '$resp_ent', '$data_fim', '$acao', '$resp_acao', '$inicio_action', '$fim_action')");
}
}
else
{
echo "NOTHING";
}
Try checking the first item in the foreach:
if ($_GET['action_ent'] != "#!##!##!#")
{
$myInputs = $_GET['action_ent'];
foreach ($myInputs as $eachInput)
{
if(empty($eachInput)) {
echo 'NOTHING';
break;
}
$valores = $eachInput;
print_r($valores);
$dummy = explode('#!#', $valores);
$acao = $dummy[0];
$resp_acao = $dummy[1];
$inic_plan_acao = $dummy[2];
$fim_plan_acao = $dummy[3];
$inicio_acc = explode("/", $inic_plan_acao);
$fim_acc = explode("/", $fim_plan_acao);
$inicio_action = $inicio_acc[2]."-".$inicio_acc[1]."-".$inicio_acc[0];
$fim_action = $fim_acc[2]."-".$fim_acc[1]."-".$fim_acc[0];
$result2 = mysql_query("INSERT INTO `demv3`.`entraves_action` (`action_id`, `ent_id`, `resp_ent`, `data_fim`,`action_desc`,`action_resp`,`action_comeco`,`action_fim`) VALUES ('0', '$ent_id', '$resp_ent', '$data_fim', '$acao', '$resp_acao', '$inicio_action', '$fim_action')");
}
}
else
{
echo "NOTHING";
}
Just be aware that if any other input besides the first one is empty it will break the loop. In order to avoid major changes in your logic you can resolve this with a counter or a boolean flag:
if(empty($eachInput) && $counter == 0) {
echo 'NOTHING';
break;
}

PHP $_POST Validation

Is there a quick and easy way to check if any of my $_POST data has the same value?
I need it as a conditional statement...
Example:
$week1 = $_POST['Week_1'];
$week2 = $_POST['Week_2'];
$week3 = $_POST['Week_3'];
$week4 = $_POST['Week_4'];
$week5 = $_POST['Week_5'];
$week6 = $_POST['Week_6'];
$week7 = $_POST['Week_7'];
$week8 = $_POST['Week_8'];
$week9 = $_POST['Week_9'];
$week10 = $_POST['Week_10'];
$week11 = $_POST['Week_11'];
$week12 = $_POST['Week_12'];
$week13 = $_POST['Week_13'];
$week14 = $_POST['Week_14'];
$week15 = $_POST['Week_15'];
$week16 = $_POST['Week_16'];
$week17 = $_POST['Week_17'];
If the values of any of the weeks = equal the value of any of the other weeks, error...
Is there a quick way to do this in PHP?
Thanks!
Chris
first though to pop in to my head:
$r=array_unique(array($week1, ...));
if (count($r) !=17){
//error
}
If the only $_POST values you have are 'Week_1' through 'Week_17' then
if (count(array_unique($_POST)) === count($_POST)) {
//all unique values, do stuff...
}
Just loop through the pairs and compare them:
$weeks=array();
foreach(range(1,17) as $i)
{
array_push($weeks,'Week_' . $i);
}
foreach(range(1,16) as $i)
{
foreach(range($i+1,17) as $j)
{
if($_POST[$weeks[$i]]==$_POST[$weeks[$j]])
{
die("Rut-roh!");
{
}
}
}

Categories