Printing multiple empty variables as "Not Available" with a specific style - php

I'm trying to print the value of empty variables as "Not available" with a specific style (class = 'not-available'). The data will be taken from multiple custom fields and some of them may have an empty value. I'm already doing this with the following code in PHP. My question: is there any alternative way to do the same more efficiently without checking each variable separately?
$na = "<span class='not-available'>Not available</span>";
$prog_auth_id = get_field('prog_auth_id');
if(empty($prog_auth_id)) $prog_auth_id = $na;
$prog_entity_cat = get_field('prog_entity_cat');
if(empty($prog_entity_cat)) $prog_entity_cat = $na;
$prog_assoc_entity = get_field('prog_assoc_entity');
if(empty($prog_assoc_entity)) $prog_assoc_entity = $na;

You can use variable variables in a loop to identify the variables that are empty or not and style them as desired:
$fields = ['prog_auth_id', 'prog_entity_cat', 'prog_assoc_entity'];
foreach($fields as $value) {
$$value = (empty($$value)) ? $na : $$value;
}
working demo

Related

Getting Single Value From Chunked Array

In an array that is chunked into blocks of 11 values, I need to know if a particular one has a TRUE value. If only one is TRUE, that's all I need and the foreach can stop after it sets a value. All I could think of to do was to make it set a SESSION value to TRUE if a match but that does not stop the loop from continuing and then I had the issue of the SESSION giving false results unless it was then unset which I did after the value was set. Seems rather an indirect way to do it so any suggestions?
$FormValues = array_chunk($Fields, $NoValues); // Group together the field values
// Check if form uses multiple selection fields and add appropriate form tags
foreach ($FormValues as $multi) :
if (isset($multi[9]) === TRUE) $_SESSION['useMulti'] = TRUE;
endforeach;
$enableMulti = (isset($_SESSION['useMulti'])) ? " enctype=\"multipart/form-data\"" : "";
unset($_SESSION['useMulti']);
Here is an example of an array and, in this case, none should return TRUE:
$Fields = array("First Name","Title",$Title,1,0,30,"","","","","",
"Quote","Quote",$Quote,4,0,30,"","",$quoteSQL,FALSE,$siteDB,
"Location","Location",$Location,1,0,30,"","","","","",
"Date","EventDate",$EventDate,41,0,15,"",TRUE,"","","",
"Time","Time",$Time,39,0,0,"","",$sqlTime,"","",
);
You can simply iterate over the original array in strides of 11, rather than using array_chunk.
To make the loop stop iterating once you've found what you want, use break.
You don't need a session variable for this, they're only for preserving values between different PHP scripts. You don't really even need another variable, you can just set the enableMulti variable in the loop.
$enableMulti = "";
for ($i = 9; i < count($Fields); $i += $NoValues) {
if ($Fields[$i] === true) {
$enableMulti = " enctype=\"multipart/form-data\"";
break;
}
}
If you really want to use foreach you do need to use array_chunk, and you can also use array_column.
$enableMulti = "";
$chunks = array_chunk($Fields, $NoValues);
foreach (array_column($chunks, 9) as $value) {
if ($value === true) {
$enableMulti = " enctype=\"multipart/form-data\"";
break;
}
}
You can also get rid of the loop entirely:
if array_search(TRUE, array_column($chunks, 9)) {
$enableMulti = " enctype=\"multipart/form-data\"";
} else {
$enableMulti = "";
}

only update if value is not empty in foreach statement

I keep getting an error Undefined property: stdClass::$ on any $li that is empty, is there a quicker way of not inserting the blank columns / fields? other than if ($li->company != "") I still want it to insert the non empty ones.
foreach ($data as $li) {
$insert['company']= $li->company;
$insert['first']= $li->first;
$insert['last']= $li->last;
$insert['email']= $li->email;
$insert['phone1']= $li->phone1;
$insert['phone2']= $li->phone2;
$insert['phone3']= $li->phone3;
$insert['address1']= $li->address1;
$insert['address2']= $li->address2;
$insert['address3']= $li->address3;
$insert['postcode']= $li->zip;
$insert['city']= $li->city;
$insert['country']= $li->country;
$insert['stage']= $li->stage;
$insert['source']= $li->source;
$insert['website']= $li->website;
$insert['user_ID']= is_user_logged_in();
$insert['owner']= is_user_logged_in();
$insert['assigneduser']= is_user_logged_in();
$insert['stage']= "Prospect";
$this->db->insert("leads", $insert);
}
Use isset() to test if the property is set, and use a default value if it isn't.
$insert['company'] = isset($li->company) ? $li->company : "";
To avoid lots of repetition, you can use a loop:
foreach (['company', 'first', 'last', ...] as $field) {
$insert[$field] = isset($li->{$field}) ? $li->{$field} : "";
}
DEMO
In your Class constructor you can set a default value for all the attributes.
If you cannot modify the constructor, an alternative to have a better readable code is use the ternary operators, an one line if and else variation
For example:
$insert['company'] = (isset($li->company))? $li->company : "";
is the same as
if(isset($li->company))
$insert['company'] = $li->company;
else
$insert['company'] = "";
Wrap it in a test for empty:
if($li->zip) {
$insert['postcode'] = $li->zip;
}

check if list of vars are empty, and if not, move to string in PHP

I have read many things around the use of isset() and empty, but am not able to find the answer I am looking for.
Basically this: A user fills in some html inputs on post, which calls a php script. Prior to calling a separate web service to look up an address, I need to create a string with all of the address elements that have been populated. Where an input field has not been populated I want to exclude it from the list.
In short:
Check posted $vars 1 to 10 to see if they contain a value.
For each one that has no value, remove it from the string. Where a value is present, add it to the string.
I have tried using empty, !empty, isset and still haven't worked it out.
Sample code:
<?php
if
(empty($Lot_no))
{ $Lot_no = $v1;
}
if (empty($Flat_unit_no))
{$Flat_unit_no = $v2;
}
$str= $v1. $v2;
?>
Do something like
$address = '';
foreach ($_POST as $post) {
if (!empty($post)) {
$address .= $post . ', ';
}
}
Here is another similar question that is similar.
Why check both isset() and !empty()
If you want to add it to an array do something like this (I'm not sure on your form input names but as an example with form input names of street, city, state
$address = [];
$addressKeys = ['street', 'city', 'state'];
foreach ($_POST as $key => $post) {
if (in_array($key, $addressKeys)) {
$address[$key] = $post;
}
}
I didn't test this but it looks fine.
Try this one. You can check the value if it is equals to 0 or not.
<?php
if((empty($Lot_no)) && ($Lot_no =='0')){
$Lot_no = $v1;
}if ((empty($Flat_unit_no)) && ($Lot_no =='0')){
$Flat_unit_no = $v2;
}
$str= $v1. $v2;
?>

composed variable after Object Operator in PHP

How can I build a composed variable while creating a variable in PHP?
(Sorry I'm not sure how to call the different elements)
This is what I'm trying to do:
$language = 'name_'.$this->session->userdata('site_lang');
for ($i=1;$i<=3;$i++) {
$data = $arraydata->$language_.$i; // problem is here
}
I would like $language_.$i to be equivalent to name_english_1, next loop name_english_2... The same way I built $language
If you want to use an expression in a computed property, you have to put the expression in braces. Also, you need to put the underscore in quotes.
$data = $arraydata->{$language."_".$i};
However, I suggest you redesign your data structure. Instead of having separate name_LANG_i properties, make a single name property whose value is a multi-dimensional array.
$lang = $this->session->userdata('site_lang');
for ($i=1;$i<=3;$i++) {
$data = $arraydata->name[$lang][$i];
// do something with $data
}
Whenever you find yourself using variable variables or variable properties, it's almost always a sign that you should be using an array instead.
First construct the field name and then use it for accessing the field value from the object $arraydata. So your code should be like this:
$language = 'name_'.$this->session->userdata('site_lang');
for ($i = 1; $i <= 3; $i++) {
$var = "{$language}_{$i}";
$data = $arraydata->$var;
// echo $data;
}

How can I shorten my code with isset values

Im am so lost. Can anyone explain how i can shorten this code. I have hundreds of these! I submit a form with input value. Whenever i dont fill in a value, i get an error. So i made these isset blocks to prevent returning the error. But i seem so unefficient! Please help...thanks
if(isset($_POST['input74'])){
$value74 = $_POST['input74'];
}else{
$value74 = "";#default value
}
if(isset($_POST['input75'])){
$value75 = $_POST['input75'];
}else{
$value75 = "";#default value
}
if(isset($_POST['input76'])){
$value76 = $_POST['input76'];
}else{
$value76 = "";#default value
you could wrap the isset in a function like this
function myIsset(&$variable, $default = "")
{
if(isset($variable))
{
return $variable;
}
else
{
return $default;
}
}
then you just call it like $value74 = myIsset($_POST['input74']);
the second argument defaults to an empty string so if you want to set the default value you can supply it or change what the default is in the function header if they will just all be the same. bellow is a screen shot showing the code working
while yes you are still going to have one line per $_POST at least you exchnge 5 lines of code with 1 line of code and the function above. you can possibly reduce this to a loop like how i explain in this answer however without seeing the form and confirming any pattern i can't give any code examples for that since what you have shown could just be a coincidence
PHP 7 has a new operator to address this specific situation: the null coalesce operator (??) replaces this:
$foo = isset($foo) ? $foo : $bar
With this:
$foo = $foo ?? $bar;
PHP has support for arrays in forms. You can name your form fields with indexes, e.g. <input type="text" name="input[74]" ... />. Then in PHP, you can access those with a for or foreach loop, because they will be available as an array (i.e. you will have $_POST["input"][74]). You could thus write something like:
$values = $_POST["input"];
for ($i = 0; $i < MAX_INPUTS; $i++) {
if (!isset($values[$i])) {
$values[$i] = ""; // default value
}
}
If for some reason you can't change the HTML side, you could still use a loop to dynamically create the field names and copy the data to an array on the PHP side, something like:
$value = array();
for ($i = 0; $i < MAX_INPUTS; $i++) {
$name = sprintf("input%d", $i);
if (isset($_POST[$name])) {
$value[$i] = $_POST[$name];
} else {
$value[$i] = ""; // default
}
}
In both proposed solutions, you only have some lines of code instead of dozens of repetitions of almost the same lines. In both examples, I assumes that your fields start with input0 and that there is a total of MAX_INPUTS fields. If not all fields exist (e.g. you only have input1, intput2, input74 and input75), you can create an array with the fields numbers:
$field_list = array(1,2,74,75);
And then use that to check your data (here the example with arrays in HTML field names):
$values = $_POST["input"];
foreach ($field_list as $num) {
if (!isset($values[$num])) {
$values[$num] = ""; // default value
}
}
Use ternaries to shorten the code:
$value74 = isset($_POST['input74']) ? $_POST['input74'] : 'Default value';
$value75 = isset($_POST['input75']) ? $_POST['input75'] : 'Default value';
$value76 = isset($_POST['input76']) ? $_POST['input76'] : 'Default value';
Or you could loop through $_POST array as well, but some filtering/validation must be done. Quick idea:
if(!empty($_POST)) {
$i = 0;
$arr = array();
foreach($_POST as $input) {
$arr[$i] = $input;
$i++;
}
}
$arr would then produce an array like
Array
(
[74] => 'value74'
[75] => 'value75'
[76] => 'value76'
)
If I understand you correctly seeing that you want to set a variable to post or otherwise default value you can do it following the below structure:
$variable = isset($_POST['name']) ? $_POST['name] : "defaultvalue";
That will set the variable of it exists otherwise set the default value specified. I hope this helps.
You could use array_merge.
You would set up your default array with all the default input values provided.
$aryDefault = ['input74'=>'', 'input75'=>'',...]
Then array_merge this with your post array, and it will fill in all the missing values. NOTE: Order is important check out the docs.
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one. If, however, the arrays
contain numeric keys, the later value will not overwrite the original
value, but will be appended.
Use array_merge($aryDefault, $_POST) so that $_POST overwrites the defaults.
Also, you can use variable variables so you can do this in a loop. If all your variable are named after your array keys, like in your example.
Full Code:
$aryDefault = ['input74'=>'', 'input75'=>'',...];
$aryFinal = array_merge($aryDefaults, $_POST);
foreach( $aryFinal as $key=>$value){
$$key = $value;
}
You could even generate $aryDefault with a loop, if its super big.
$aryDefault = array();
for(i=0;i<=100;i++){
$aryDefault["input$i"] = "";
}
You can create a simple function to encapsulate the code before PHP 7:
function post($key, $default = null){
return isset ($_POST[$key])?$_POST[$key]:$default;
}
Since PHP 7 (using the null coalescing operator (??)):
function post($key, $default = null){
return $_POST[$key] ?? $default;
}
or better whithout function just simple (as mentioned above)
$value74 = $_POST['input74'] ?? ''; #default value
$value75 = $_POST['input75'] ?? ''; #default value
$value76 = $_POST['input76'] ?? ''; #default value

Categories