Better way to write if sequence - php

I've a sequence of if statements and I can't figure a better way to write it here's it is :
$a='';$b='';$c='';
if($row->nA!=0){
$a = $row->nA;
}
if($row->nB!=0){
$b = $row->nB;
}
if($row->nC!=0){
$b = $row->nC;
}
It simple but I can't find how write it better than this

There's nothing completly wrong with your way.
If you want to write something else, try it like this:
$a = ($row->nA != 0) ? $row-nA : '';
$b = ($row->nB != 0) ? $row-nB : '';
$c = ($row->nC != 0) ? $row-nC : '';
But, like i said, there is nothing wrong with your way ;)

Sascha Presnac is right - there is nothing wrong with the way you're doing it. However, it might be useful if you tidy up your code a little.
$a = '';
$b = '';
$c = '';
if ($row->nA != 0) {
$a = $row->nA;
}
if ($row->nB != 0) {
$b = $row->nB;
}
if ($row->nC != 0) {
$b = $row->nC;
}
Using extra lines to write your code is not a problem. It is better to be more spread out and easily readable, than scrunched up and hard to read :). But if you want to do it in as few a lines as possible then go for Sacha Presnac's approach :)

If you have yo do it for a lot of variables you could do it with
$variables = ['a', 'b', 'c'];
foreach ($variables as $variable)
{
$$variable = ($row->{"n" . strtoupper($variable)} != 0) ? $row->{"n" . strtoupper($variable)} : '';
}

Related

$_POST better writing quality

I have this code :
if(isset($_POST['prenom2'])){
$t['prenom2'] = $_POST['prenom2'];
}else{
$t['prenom2'] = '';
}
if(isset($_POST['nom2'])){
$t['nom2'] = $_POST['nom2'];
}else{
$t['nom2'] = '';
}
if(isset($_POST['prenom3'])){
$t['prenom3'] = $_POST['prenom3'];
}else{
$t['prenom3'] = '';
}
etc (there are 5 or 6 fields I need to test).
There must be a better way of doing this, like if a given index of POST isn't set, that index is...
Thanks
You can use foreach.
$indexes = array('prenom2', 'nom2', ...);
$t = array();
foreach ($indexes as $i) {
$t[$i] = isset($_POST[$i]) ? $_POST[$i] : '';
}
print_r($t);
If you don't want to use if..else.. condition then you can use ternary : operator as
$t['prenom2'] = (isset($_POST['prenom2'])) ? $_POST['prenom2'] : '';
$t['nom2'] = (isset($_POST['nom2'])) ? $_POST['nom2'] : '';
Basically the same as the answer from Matei but moved in a function to reduce duplicate code.
Parameter $t is your final array and $key is a string representing the array index. The final $t array is also returned so there is no need for passing a reference.
function setT($t, $key)
{
$t[$key] = isset($_POST[$key]) ? $_POST[$key] : '';
return $t;
}
$t = setT($t, 'prenom1');
$t = setT($t, 'prenom2');
$t = setT($t, 'prenom3');
Based on your real problem, you may choose one of these:
for($i=1; $i<6; $i++){
$t['prenom'.$i] = (isset($_POST['prenom'.$i])) ? $_POST['prenom'.$i] : '';
$t['nom'.$i] = (isset($_POST['nom'.$i])) ? $_POST['nom'.$i] : '';
}
or
$indexes = array('prenom2'=>'', 'nom2'=>'', ...);
$t = array_merge($indexes,$_POST);

PHP combined operator for &&?

I have code like this:
$finalResult = true;
$finalResult = $finalResult && function_01();
// some code here
$finalResult = $finalResult && function_02();
// some many lines of code here
$finalResult = $finalResult && function_XX();
And I'm looking for a way how to shorten the code (just for a human-readibility reasons) to something like:
$finalResult = true;
$finalResult &&= function_01();
// some code here
$finalResult &&= function_02();
// some many lines of code here
$finalResult &&= function_XX();
But of course this doesn't work and operator &= is not for boolean values, but for binary.
How should I do this ?
Thanks.
$names = array('function01','function02'...);
$result = true;
foreach($names as $caller)
{
$result = $result && $caller();
}
otherwise instead of $caller() you could look for call_user_func ( http://us3.php.net/call_user_func )
it's not really fantastic, but it's shorter :/ not a big deal
edit:
uhm... i guess that after your edit this solution is not more functional... should i delete it ?
I would also reconsider the logic of your code by adding a class that makes these checks: if all the checking logic is in a class whose purpose is just that you could surely benefit of readability
Stormsson's but improved - finish as soon as you know the result:
$names = array( 'function01','function02'... );
$result = true;
foreach( $names as $caller )
{
if ( $result == false ) break; // short circuit
$ret = $caller()
if ( $ret == false )
{
$result = false;
break; // short circuit
}
$result = $result && $ret;
}
OK, after all it seems I will not get it any simpler than original.
For those of you who don't understand why I want to have it in some "short" form - only reason was to have it shorter and nicer. Just the same reason why there is possibility to write $a += 3 just for beauty.
Anyway, thanks to everybody :)

A way to neaten this PHP code

I have the following PHP code:
<?php
//code above
$pic_1 = $afil['image_1'];
$pic_2 = $afil['image_2'];
$pic_3 = $afil['image_3'];
$pic_4 = $afil['image_4'];
$pic_5 = $afil['image_5'];
$pic_6 = $afil['image_6'];
$pic_7= $afil['image_7'];
$pic_8 = $afil['image_8'];
$pic_9 = $afil['image_9'];
$pic_10 = $afil['image_10'];
if ($pic_1 = "")
{
$pic_1 = //defaultpic - to be defined, same as below
}
if ($pic_2 = "")
{
$pic_2 = //defaultpic
}
?>
Rather than repeat these "if" statements for each picture (up until $pic 10) i just wondered if somebody could point out a more elegant and efficient way of doing it. I am quite new to php and this is a new situation i have encountered. Thanks a lot in advance.
Use arrays and loop through them with just 1 if statement, like this,
foreach($afil as $k => $v) {
if(empty($v))
$afil[$k] = ...//default pic
}
Or, if you are keen to have an additional array $pics (for future use maybe),
foreach($afil as $k => $v) {
$pics[$k] = $v;
if(empty($v))
$pics[$k] = ...//default pic
}
Also, = is an assignment operator. For comparison (or condition check), you need to use == or === (type safe).
Edit:
$afil = mysql_query(...);
while($row = mysql_fetch_array($afil)) {
//In here, say you create an array $result_rows with all the rows
$result_rows[] = $row;
}
Then, use $result_rows in the foreach.
Arrays is your golden solution:
$pic = array('image_1', 'image_2', 'image_3'....);
for ($i = 0; $i < count($pic); $i++){
if ($pic[$i] == ""){
$pic[$i] = //defaultpic -
}
}

How to change the variable being assigned via condition?

I want to change the variable being assigned based on condition, and I can seem to get it working.
$condition = false;
($condition !== false ? $array[1][$condition] : $array[1]) = 'Test';
In this example, if $condition isn't false, I want to assign the string "Test" to $array[1][$condition]. Otherwise, assign it to $array[1]
I can easily do this like this:
if ($condition !== false) {
$array[1][$condition] = 'Test'; }
else {
$array[1] = 'Test'; }
But due to the nature of the code this can get quite cluttered, which is why I wish for it to be an inline conditional statement.
Thanks for any help!
$condition = false;
$array[1][$condition] = ($condition !== false ? 'Test' : $array[1]);
$condition !== false ? $array[1][$condition] = "Test" : $array[1] = "Test";
The result of the ternary operator is not a reference, so you can't use it as the left-hand side of an assignment.
You might be able to use variable variables and references, but this might just add complexity without providing any real benefit.
Something like this:
$a =& $array[1];
$b =& $array[1][$condition];
$var = ($condition !== false ? 'b' : 'a');
$$var = 'Test';

Assign a value conditionally after array is set with PHP

If I wanted to do something like this:
<?php
$numbers = array(
"a_pos" => 0,
"b_pos" => 2,
"c_pos" => 3
);
if ($numbers["a_pos"] == 0)
$a_pos_txt = TRUE;
if ($numbers["b_pos"] == 0)
$b_pos_txt = TRUE;
if ($numbers["c_pos"] == 0)
$c_pos_txt = TRUE;
?>
(Just assign TRUE to $a_pos_txt because it is equal to 0)
What would be that smart way to do it? I´m sure there must be a way to do it in "one step".
Thanks in advance!!
Please ask for any needed clarificarion.
Not really sure what you're trying to accomplish, as there may be a better approach overall, but to answer your question, you can skip the if statements like so:
$a_pos_txt = $numbers["a_pos"] == 0;
$b_pos_txt = $numbers["b_pos"] == 0;
$c_pos_txt = $numbers["c_pos"] == 0;
If the $numbers is an array, you can do a loop to avoid repeating the similar pattern,
such as
foreach ($numbers as $key=>$val)
{
if ($val==0)
{
${$key."_txt"}=true;
}
}

Categories