Combining several targeted value's / variable in one piece - php

We currently use the following piece of PHP code to target (change) several variables. Though this works, is there some way to shorten it? I am guessing there is a shorter way, however we don't have any PHP knowledge.
if($form_id == 10767){
if($data['element_id'] == 13){
if(empty($data['value'])){
$data['value'] .= '';
}else{
$data['value'] = '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
}
if($form_id == 10767){
if($data['element_id'] == 14){
if(empty($data['value'])){
$data['value'] .= '';
}else{
$data['value'] = '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
}
if($form_id == 10767){
if($data['element_id'] == 16){
if(empty($data['value'])){
$data['value'] .= '';
}else{
$data['value'] = '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
}
if($form_id == 10767){
if($data['element_id'] == 17){
if(empty($data['value'])){
$data['value'] .= '';
}else{
$data['value'] = '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
}
I think it's possible to combine those element_id's into one single line, instead of targeting them seperately, right?
Something like this:
if($data['element_id'] == 13,14,16,17)
I tried a few things myself, but every time I get an error or break things.
Thank you kindly in advance.

If you load your targets into an array and then us in_array(needle, haystack) it can be easily reduced.
With a ternary operator instead of an IF it can be even more reduced.
$target_ids = array(13,14,16,17);
if($form_id == 10767){
if( in_array($data['element_id'], $target_ids)) {
$data['value'] = empty($data['value']) ? '' : '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}

You're currently use the same if-statements several times, which isn't needed:
Then you should look into the documentation about "if" and about Logical Operators and you will find how to write "or":
if($form_id == 10767){
if($data['element_id'] == 13 || $data['element_id'] == 14 || ...etc... ){
if(!empty($data['value'])){
$data['value'] = '<p style="font-size:13px;">'.$data['value'].'</p>';
}
}
}
I also removed $data['value'] .= ''; on empty, since it doesn't do anything. (notice the ! before empty() which means that it validates if the value is not empty.)

Related

if condition with foreach loop for array in php

is it any way to stop this repeated data.
if ($employees_csa[0]->csa_taken == 2 && $employees_csa[1]->csa_taken == 2 && $employees_csa[2]->csa_taken == 2 && $employees_csa[3]->csa_taken == 2 && $employees_csa[4]->csa_taken == 2 && $employees_csa[5]->csa_taken == 2 && $employees_csa[6]->csa_taken == 2 && $employees_csa[7]->csa_taken == 2) {
echo "data";
}
i tried for key range(0 , 8)
like this
foreach (range(0, count($employees_csa)) as $number) {
if ($employees_csa[$number]->csa_taken == 2) {
echo "data";
}
}
i tried that way not get any succes. i any another way to write easy condition.
You can loop arrays out of the box:
$all_taken = true;
foreach ($employees_csa as $employee) {
if ($employee->csa_taken != 2) {
$all_taken = false;
break;
}
}
if ($all_taken) {
echo 'data';
}
Another approach would be array_reduce() but this doesn't abort looping when there's already an answer:
$all_taken = array_reduce($employees_csa, function ($all_taken, $employee) {
if ($employee->csa_taken != 2) {
return false;
}
return $all_taken;
}, true);
if ($all_taken) {
echo 'data';
}
Alternatively, you could do it like this using array_column to pull out all the csa_taken properties, then reducing to 1 item if they are all the same with array_unique() and then checking that the same value is the expected number 2 with reset().
$csa_taken = array_column($employees_csa, 'csa_taken');
if (reset($csa_taken) === 2 && count(array_unique($csa_taken)) === 1) {
echo 'data';
}
Reusable function version: https://3v4l.org/4kYiE
A simple for-loop could work
$condition_met=true;
for($i=0;$i<8;++$i){
if( $employees_csa[$i]->csa_taken != 2){
$condition_met=false;
break;
}
}
if($condition_met===true){
//success
}
else{
//fail
}
A simple method could be done like
foreach($employees_csa as $singleEmployee){
if($singleEmployee->csa_taken == 2){
echo "data";
}
}

PHP - IF doing all the time only first condition, why? [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 5 years ago.
why the IF(the lastest one with else if and else) is doing all the time only first condition and only the first part ($filtry_1value[$key] = 'min_cena'), even if the condition shouldnt be true. I have another solution (less dynamic), if I will not fix this one, but I would like to know, why it is not working... I think it will be a trivial thing, but I cannot see it.
PS: I am working with laravel.
$filtry_1value = ['stat', 'lokalita', 'patro', 'min_cena', 'max_cena', 'min_uzitna_plocha', 'max_uzitna_plocha'];
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] = 'min_cena' OR $filtry_1value[$key] = 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] = 'max_cena' OR $filtry_1value[$key] = 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}
may be-
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}
You need to use the double equal sign for comparisons. == not a single =
Your if's should look like:-
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
// ...
} elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
// ...
}

Checking Multiple $_GET variables if equals a string

if(isset($_GET['a']) || isset($_GET['b']) || isset($_GET['c'])){
if(($_GET['a'] || $_GET['b'] || $_GET['c']) == "x"){
echo "YES";
} else {
echo "NO";
}
}
in this php code, i'm trying to check if one of those requests isset and if one of them value == 'x' or not, But the 2nd part if(($_GET['a'] || $_GET['b'] || $_GET['c']) == "x") doesn't work as intended at all, I wrapped it inside () hoping it would work, In this condition, do i have to separate it as i did inthe isset() part? or is there a better method to do that?
This is likely what you are looking for
UPDATE - I just changed || to && for the last condition in case you were quick to try it out.
if( (isset($_GET['a']) && $_GET['a'] == "x") || (isset($_GET['b']) && $_GET['b'] == "x") || (isset($_GET['c']) && $_GET['c'] == "x")){
echo "YES";
} else {
echo "NO";
}
If you have to write a lot of conditionals you could use one of the following:
Using a foreach and a conditional:
$either_abc_is_x = function() {
$keys = ['a','b','c'];
foreach($keys as $key)
if(isset($_GET[$key]) && $_GET[$key] == "x")
return true;
return false;
};
echo $either_abc_is_x() ? 'YES' : 'NO';
Using a an array filter with a conditional:
$get_abc_keys_equal_to_x = array_filter(['a','b','c'], function($v) {
return isset($_GET[$v]) && $_GET[$v] == 'x';
});
echo $get_abc_keys_equal_to_x ? 'YES' : 'NO';
Array gymnastics:
$either_abc_is_x = isset($_GET) && in_array('x', array_intersect_key($_GET, array_flip(['a','b','c'])));
echo $either_abc_is_x ? 'YES' : 'NO';

PHP ternary operators

I have written a ternary function in PHP and it seems to work, although I am not sure if it is correct, can someone take a look and tell me if it is right?
I have added the ternary and the if of what should be happening.
//Foreach Loop
foreach ($post as $item) {
//If of what should occur
if ($passed == true) {
if (is_numeric($item)) {
if ($item > 0) {
$passed = true;
}
else {
$passed = false;
}
}
else {
if ($item != "") {
$passed = true;
}
else {
$passed = false;
}
}
//Ternary operator.
$passed = (is_numeric($item) ? ($item > 0 ? true : false) : ($item != "" ? true : false));
}
else {
return $passed;
}
}
please have a look on corrected code
$passed = (is_numeric($item))?($item>0?true:false):($item !="" ? true:false);
Honestly I do not really understand why you do not use a
if (!empty($item)) {
$passed = true;
} else {
return false;
}
In any case, ternaries are less readable than if /elseif / else, they are also slower (note that it is not an universal truth but a more general use case thing http://fabien.potencier.org/the-php-ternary-operator-fast-or-not.html).
I would recommend, if you really need all these if and elses to keep them rather than using ternaries (for readability's purpose).

if else simple beginner issue

Good day guys,
I've made a sweet favorites function with php mysql and ajax, and its working great. Now I want to show 'favorite' when favorite = 0 and show 'unfavorite' when favorite = 1
if ($favorites == 0) {
$favorite = 'Favorite';
}
if ($favorites == 1) {
$unfavorite = 'unFavorite';
}
and echo it in the row as :
<div id="favorites">' .($favorite). ' ' .($unfavorite). '</div>
The problem is: when favorite = 0, both $favorite and $unfavorite are being shown. When favorite = 1 only $unfavorite is being shown correctly. Of course it should be $favorite OR $unfavorite. I assume the problem is clear and simple to you, please assist :)
Thanks in advance
It's easier to use just one variable:
$text = ''
if ($favorites == 0) {
$text = 'Favorite';
} else {
$text = 'unFavorite';
}
...
echo $text;
If you want to check $favorite, you are using the wrong variable in your control statement. Also, it is better coding practice to use elseif rather than if for that second if. One more thing: it's easier to manage one resulting variable.
$output = "";
if ($favorite == 0) {
$output = 'Favorite';
}
elseif ($favorite == 1) {
$output = 'unFavorite';
}
...
echo $output; // Or whatever you want to do with your output
Is $favorites an integer?
Anyway try using three equal signs (===) or else instead of the second if:
if ( $favorites === 0 )
{
// ...
}
else // or if ($favorites === 1)
{
// ...
}
You're making a toggle, so you only need one variable:
if(empty($favourites)){
$fav_toggle = 'Favorite';
} else {
$fav_toggle = 'unFavorite';
}
echo $fav_toggle;
Same code is working on me if I assigned $favorites = 0; or $favorites = 1;
You can also use if else
$favorites = 1;
if ($favorites == 0) {
$favorite = 'Favorite';
}
else if ($favorites == 1) {
$unfavorite = 'unFavorite';
}

Categories