Multiple lines if statements - php

I am checking around 20 variables like the following and I was wondering if there is a faster way (less lines) to do the same:
if ($data1 == 1) {
$res1 = "Yes";
} else {
$res1 = "No";
}
if ($data2 == 1) {
$res2 = "Yes";
} else {
$res2 = "No";
}
if ($data3 == 1) {
$res3 = "Yes";
} else {
$res3 = "No";
}
etc..

There are a few ways:
1) foreach loop:
$array = [$data1, $data2, $data3];
foreach ($array as $key => $value)
{
${'res'. $key} = ($value == 1 ? 'yes' : 'no');
}
Although as Qirel pointed out, this probably isn't the best thing to do. If you need to name new values $name. $x then it's probably better as an array:
$array = [$data1, $data2, $data3];
$res = [];
foreach ($array as $key => $value)
{
$res[$key] = ($value == 1 ? 'yes' : 'no');
}
2) function:
function checkVal($value)
{
return ($value == 1 ? 'yes' : 'no');
}
$res1 = checkVal($data1);
3) ternary - not necessarily not repeating code, but it's shorter:
$res1 = ($data1 == 1 ? 'yes' : 'no')
$res2 = ($data2 == 1 ? 'yes' : 'no')
$res3 = ($data3 == 1 ? 'yes' : 'no')

This should also work -
// number of variables to check
$num = 3;
// Loop for checking all the variables as per naming convnetions followed
for ($i = 1; $i <= $num; $i++) {
// set yes/no depending on the data set
${'res' . $i} = ${'data' . $i} == 1 ? 'yes' : 'no';
}

I don't know the context but from what I can see my advice is to create an array of $data1, $data2, $dataN and loop all these values to create another array with all checks
$values = [$data1, $data2, $data3, $data4];
$responses = array_reduce($values, function ($a, $b) {
$a[] = 1 === $b;
return $a;
}, []);

Related

Value not saving outside foreach loop

I update my code from PHP 5 to PHP 7 and i got problem with foreach loop. I loocked wor answers here, but none is working. Or i dont understand where i have problem
function getStructure($pid = 0, $expand = array(), $alevel = 0)
{
$struct = array();
if ( $alevel > $this->levelCount) $this->levelCount = (int)$alevel;
$str = $this->dbStructure->getStructure($pid);
foreach ($str as &$row)
{
if ($row["type"] == STRUCT_PAGE)
{
$row["editLink"] = "editPage";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_MODULE)
{
$row["editLink"] = "editModule";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_LINK)
{
$row["editLink"] = "editLink";
$row["target"] = "_blank";
}
elseif ($row["type"] == STRUCT_CATALOG)
{
$row["editLink"] = "editCatalog";
$row["target"] = "_self";
}
$row["childrens"] = $this->getStructure((int)$row["id"], $expand, $alevel+1);
if ($row["type"] == STRUCT_CATALOG and isset($row["childrens"][0]["shortcut"]))
{
$row["shortcut"] = $row["childrens"][0]["shortcut"];
$row["target"] = $row["childrens"][0]["type"] == STRUCT_LINK ? "_blank" : "_self";
}
$struct[] = $row;
}
unset($row);
return $struct;
}
All the time $struct is NULL and I need to be multidimensional array
This code by itself is good. Has no problems, only ampersand is not needet. The problem was in different place. Sorry for spam

MySQLi why am I only getting 1 result?

There are three "BC" in the result_category but I am only getting 1 result. This is for a personality quiz. Please Help. I also tried $query = "SELECT result FROM quiz_map where result_category = 'BC'"; but still, only 1 result is showing.
$result = mysqli_query($link, $query);
$cat_a = $cat_b = $cat_c = $cat_d = $cat_e = 0;
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$cat = $row['category'];
if ($cat == "A") {
$cat_a += 1;
} elseif ($cat == "B") {
$cat_b += 1;
} elseif ($cat == "C") {
$cat_c += 1;
} elseif ($cat == "D") {
$cat_d += 1;
} elseif ($cat == "E") {
$cat_e += 1;
}
}
$array = array('A' => $cat_a, 'B' => $cat_b, 'C' => $cat_c, 'D' => $cat_d, 'E' => $cat_e);
$str = '';
foreach ($array as $i => $value) {
if ($value >= 6) {
$str = $i;
break;
} elseif ($value >= 2) {
$str .= $i;
}
}
$var = sort($array);
$query = "SELECT result FROM quiz_map where result_category = '$str' LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
echo $row[0];
?>
There's many things wrong with your code!
As pointed by #IsThisJavascript and #Cashbee:
You are executing a query with a LIMIT 1 statement, it will only return one record.
As pointed by myself:
Doing echo $row[0] will have the same result, if you are only echoing the first value of the array you can't expect to have multiples can you?
As pointed by #IsThisJavascript:
You need to loop the results array, like so:
while($row = mysqli_fetch_array($result)){
echo $row['result_category'];
}
Consider switching the query from a '=' to a '%like%' statement, to maximize results if you want to get the values that partionaly cointain the string.

How to get all values between two array values in php?

How can I find all values between two array items (including start and end value)?
Example:
array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P')
Input: $arr, 'EX', 'F'
Output: 'EX', 'VG', 'G', 'F'
Thanks in advance..
$array = array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P');
$start = "3X";
$end ="F";
$new_array = [];
$i=0;$go=false;
foreach ($array as $element) {
if($go){
$new_array[$i] = $element;
$i++;
}
if($element==$start){
$go = true;
}
if($element==$end){
$go = false;
}
}
$total_elems_new = count($new_array);
unset($new_array[$total_elems_new-1]);
print_r($new_array);
Testeed on PHP 5.6
Try:
$arr = array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P');
function findValuesBetweenTwoItems($arr, $start, $end) {
$result = [];
$has_started = false;
foreach ( $arr as $item->$value ) {
if( ( $item != $end && $has_started ) || $item == $start) {
array_push($result, $value);
$has_started = true;
}
if( $item == $end ) {
array_push($result, $value);
return $result;
}
}
$my_values = findValuesBetweenTwoItems($arr, 'EX', 'F');
var_dump($my_values);
Try this:
$array = array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P');
$arrayKeys = array_keys($array);
$input1 = '3X';
$input2 = 'F';
if(in_array($input1,$array) && in_array($input2,$array)) {
if (array_search($input1, array_keys($array)) >= 0) {
if (array_search($input2, array_keys($array)) >= 0) {
if (array_search($input1, array_keys($array)) < array_search($input2, array_keys($array))) {
echo "Keys in between: ";
for ($i = array_search($input1, array_keys($array)); $i <= array_search($input2, array_keys($array)); $i++) {
echo $array[$arrayKeys[$i]] . ", ";
}
} else {
echo "Keys in between: ";
for ($i = array_search($input2, array_keys($array)); $i <= array_search($input1, array_keys($array)); $i++) {
echo $array[$arrayKeys[$i]] . ", ";
}
}
} else {
echo "Value not found!";
}
} else {
echo "Value not found!";
}
} else{
echo "Value not found!";
}
$from = 'EX';
$to = 'F';
$result = null;
$state = 0;
foreach ($a as $k => $v) {
if (($state == 0 && $from === $v) || ($state == 1 && $to === $v))
$state++;
if ($state && $state < 3)
$result[$k] = $v;
elseif ($state >= 2)
break;
}
if ($state != 2)
$result = null;
The loop searches for the first occurrence of $from, if $state is 0 (initial value), or the first occurrence of $to, if $state is 1. For other values of $state, the loop stops processing.
When either $from, or $to is found, $state is incremented. The values are stored into $result while $state is either 1 ($from is found), or 2 ($to is found).
Thus, $state == 2 means that both values are found, and $result contains the values from the $a array between $from and $to. Otherwise, $result is assigned to null.

Inserting an item after specific array pattern

I would like to insert an item after a specific pattern. In my case I would like to insert x after every second a in an array. After six'th a my code does not work properly:
$array = array("a","a","a","a","a","a","b","a","a");
$out = array();
foreach ($array as $key=>$value){
$out[] = $value; // add current letter to new array
if($value=='a' && $array[$key-1]=='a' && $out[$key] !='x'){ // check if current and last letter are a
$out[] = 'x'; // if so add an x to the array
}
}
print_r($out);
Correct answer at the end
Is it that what are you looking for?
<?php
$array = array("a","a","a","a","a","a","b","a","a");
foreach ($array as $key => $value){
if ($key == 0 || $key == 1) {
$array[$key] = $value;
} elseif($array[$key-1] == 'a' && $array[$key-2] == 'a' && $array[$key] == 'a') {
$array[$key] = 'x';
} else {
$array[$key] = $value;
}
}
$count = count($array);
if ($array[$count-1] == 'a' && $array[$count-2] == 'a') {
$array[] = 'x';
}
print_r($array);
?>
If I understand correctly, after 2 a you want to put x into new array.
UPDATE
Please check now. There will be added a new element x if last two are a in array.
With exceptions, but still working:
<?php
$array = array("a","a","a","a","a","a","b","a","a");
foreach ($array as $key => $value){
if($array[$key-1] == 'a' && $array[$key-2] == 'a' && $array[$key] == 'a') {
$array[$key] = 'x';
}
}
$count = count($array);
if ($array[$count-1] == 'a' && $array[$count-2] == 'a') {
$array[] = 'x';
}
print_r($array);
?>
UPDATE - Correct code
I think code below will fit all your needs:
<?php
$arr = array("a","w","a","d","a","a","b","a","a", "w");
$arr_count = count($arr);
for ($i = 0; $i < $arr_count; $i++){
if (!empty($arr[$i+1]) && $arr[$i] == $arr[$i+1]) {
$first_half = array_slice($arr, 0, $i+2);
$second_half = array_slice($arr, $i+2, $arr_count);
if (count($second_half) > 0) {
$arr = array_merge($first_half, ["x"], $second_half);
}
}
}
$count = count($arr);
if ($arr[$count-1] == 'a' && $arr[$count-2] == 'a') {
$arr[] = 'x';
}
print_r($arr);
?>
As it was mentioned in the comment, you sure can use regular expression in this particular situation:
$pattern = '/a{2}/';
$replacement = '$0x';
$out = str_split(preg_replace(
$pattern,
$replacement,
implode('', $array)
));
Basically, we gluing the characters together (using implode) to form the string and then replacing every "aa" with "aax". After that we split string back to the array using str_split.
Here is demo.

codeigniter replace array values in model

I have been going around in circles with a multidimensional array replace..
I need to replace numbers stored in a DB that relate to a status type.. If I did this in the view it would work but it wont seem to replace in the model?
function fetch_shipments($orgID){
$this->db->select('shipID, shipRef, shipCarrier, shipOrigin, shipDestination, shipQty, shipStatus');
$this->db->where('orgID', $orgID);
$query = $this->db->get('shipments');
$result = $query->result_array();
foreach($result as $row) {
foreach ($row as $key => $val) {
$key == 'shipStatus' && $val == 0 ? $val = 'Current' : $val;
$key == 'shipStatus' && $val == 1 ? $val = 'Pending' : $val;
$key == 'shipStatus' && $val == 2 ? $val = 'Complete' : $val;
}
}
return $result;
}
Has really left me scratching my head, I know this kind of foreach works as I use it all the time... I feel I am missing something (perhaps obvious) but I just cant put my finger on it. I even tried doing the replace at the object level before outputting an array but couldn't get that to work either.
you should save it on your $result variable. not in $val
foreach($result as $k => $row) {
foreach ($row as $key => $val) {
$key == 'shipStatus' && $val == 0 ? $result[$k][$key] = 'Current' : $val;
$key == 'shipStatus' && $val == 1 ? $result[$k][$key] = 'Pending' : $val;
$key == 'shipStatus' && $val == 2 ? $result[$k][$key] = 'Complete' : $val;
}
}
return $result;
Or you could remove the inner loop
foreach($result as $k => $row) {
if($row['shipStatus']==0){
$result[$k]['shipStatus'] = 'Current';
}elseif($row['shipStatus']==1){
$result[$k]['shipStatus'] = 'Pending';
}else{
$result[$k]['shipStatus'] = 'Complete';
}
}
return $result;
I believe placing a & before your loop variable should solve your problem, as then the reference would get updated.
So your loop would start something like this
foreach($result as &$row) {
foreach ($row as $key => &$val) {

Categories