Add to an array only if a variable is set [duplicate] - php

This question already has answers here:
PHP - Checking if array index exist or is null [duplicate]
(3 answers)
Closed 8 years ago.
I have this array I'm doing like so:
Turns out some of those var aren't always set which cause undefined index issues when trying to inserting it into the db?
Is there a quick way to check each value is set before adding it to the array?
$show_insert = array(
'title' => $show_data['title'],
'thetvdb_id' => $show_data['tvdbid'],
'release_date' => $show_data['FirstAired'],
'lastupdatethetvdb' => $show_data['lastupdatethetvdb'],
'moviedb_id' => $show_data['moviedb_id'],
'imdb_id' => $show_data['IMDB_ID'],
'img_id' => $show_data['tvdbid'],
'media_type' => 1,
'status' => $show_data['status'],
'length' => $show_data['runtime'],
'network' => $show_data['network'],
'overview' => $show_data['overview'],
'seasons' => $show_data['seasons'],
'episodes' => $show_data['episodes'],
'homepage' => $show_data['homepage'],
'last_airdate' => $show_data['last_air_date'],
'vote_average' => $show_data['vote_average']
);

You can use the ternary operator and isset(). We're checking if the variable and key are set (the part before ?). If it is set, use that variable (the part between ? and :) and if not, set to blank (the part after :).
Ternary operator works like:
$variable = ( comparison ? if true : if false );
Thus:
$show_insert = array(
'title' => ( isset( $show_data['title'] ) ? $show_data['title'] : '' ),
'thetvdb_id' => ( isset( $show_data['tvdbid'] ) ? $show_data['tvdbid'] : '' ),
[etc.]
);

if (isset($show_data['title']) {
$show_insert[title] = $show_data['title'];
}
This basically means that if $show_data[title] has been initialized then it will add it to the $show_insert array under the key 'title', if it has not been set, nothing will happen so there will be no array key 'title'
or for large arrays you could have:
public function check_set($array, $variable = null, $key_name)
if ($variable != null) {
$array[$key_name] = $variable;
}
check_set($show_insert, $show_data[title], $title = '"title"');

Expanding on the other answer:
I would use a function to simplify all that typing, also, I would use empty() instead of isset() but if you're just setting it to an empty string I suppose that part doesn't matter much.
function checkVal($val, $show_data){
return empty($show_data[$val]) ? "" : $show_data[$val];
}
$show_insert = array(
'title' => checkVal('title',$show_data),
'thetvdb_id' => checkVal('tvdbid',$show_data)
);

Related

How to discover structure of value in PHP returned from library function? Does not behave as expected, seems to return different values for same key [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 7 months ago.
Have not coded PHP for many years, but trying a wordpress plugin.
I am having a strange problem with some array values returned by a function.
This specific problem does not matter, the problem really is if dealing with values returned by functions, how do you check the structure returned?
I have an array built with the statement:
$args = array(shortcode_atts(OFP_Posts::get_default_args($dev_mode), $atts));
and when I pass that array into a static function, I get this strange behaviour:
static function get_recent_posts($args = array()) {
$dm = $args['date_modified'];
$jargs = json_encode($args);
echo "<p>at top, mod date:$dm:</p><p> $jargs</p>";
I get a different value for 'date_modified' from the '$dm' variable, to that in the json. The one in the json is what I would expect.
output from echo:
at top, mod date::
[{"dev_mode":"simpl","limit":5,"offset":0,"order":"DESC","orderby":"date","cat":[],"tag":[],"taxonomy":"","post_type":["post"],"post_status":"publish","ignore_sticky":1,"exclude_current":1,"excerpt":false,"length":10,"date":" ","date_relative":"","date_modified":"yes","css":"","cssID":"","css_class":"","before":"","after":""}]
Note: $dm seems to be an empty string, and yet "date_modified" is set to "yes".
I must be doing something fundamentally wrong. Any suggestions appreciated.
#ADyson suggested using var_export($args) ... which I think has provided the answer. The data returned from short_code_atts does not make a simple array.
Thank you #ADyson
array ( 0 => (object) array( 'dev_mode' => 'simpl', 'limit' => 5, 'offset' => 0, 'order' => 'DESC', 'orderby' => 'date', 'cat' => array ( ), 'tag' => array ( ), 'taxonomy' => '', 'post_type' => array ( 0 => 'post', ), 'post_status' => 'publish', 'ignore_sticky' => 1, 'exclude_current' => 1, 'excerpt' => false, 'length' => 10, 'date' => ' ', 'date_relative' => '', 'date_modified' => 'yes', 'css' => '', 'cssID' => '', 'css_class' => '', 'before' => '', 'after' => '', ), 'date_modified' => 'maybe: ', )
Note: Solved. Following the suggestion to add var_export, I had all that was needed to fix the errors. Lesson is data may not be what you expect, and var_dump or var_export are the ways to check.
This answer really came from ADyson.
If picking up PHP either for the first time, or when rusty, and having trouble with arrays or object, use var_export or var_dump to check the structure is as expected, and see what is going on.

PHP put an if command in an array [duplicate]

This question already has answers here:
Using an If-else within an array
(10 answers)
Closed 4 years ago.
This is a bit of an odd one. I am building an array in PHP and then encoding it to JSON before I spit it out.
$arr = array (
'reportDescription' =>
array (
if ($queryType == "realtime")
{
'source' => 'realtime',
}
'reportSuiteID' => 'rbsglobretailprod',
'dateGranularity' => $queryGran,
'dateFrom' => $queryFrom,
'dateTo' => $queryTo,
'elements' =>
array (
0 =>
array (
'id' => $queryElement,
),
),
'metrics' =>
array (
0 =>
array (
'id' => $queryMetric,
),
),
),
);
I am trying to get it to add a line to the array if the query type is realtime. This is what I tried but I'm not sure if it's possible to do this, and if it's not, I'm not sure how I should approach it. The error I get below suggests it may not be possible:
Parse error: syntax error, unexpected 'if' (T_IF), expecting ')'
You should do it as two separate calls:
$array = ['your', 'array', 'with', 'fields']
if ($queryType === 'realtime') {
$array[] = ['source' => 'realtime'];
}
Obviously change out the values with your expected values, but that should do the job. You could also append like so if you wanted it at root level:
if ($queryType === 'realtime') {
$array['source'] = 'realtime';
}

Unset the key in multidimensional array is not working

I am trying to unset the key which is equal to 'null' in my multidimensional array but the codes I've work with is not working so I tried to run it online. But even in online it does not work so I think there is something wrong in my codes.
My link for code is https://eval.in/591584
And this is my array:
$array = array(
'6' => array(
'null' =>array(
'null'=>array(
'11:04'=>array(
'id' => '22'
)
)
),
'1'=>array(
'2'=>array(
'11:04'=>array(
'id' => '22'
)
)
),
)
);
What I want is to remove the key with name null.
The output I want is below where the null key is unset:
$array = array(
'6' => array(
'1'=>array(
'2'=>array(
'11:04'=>array(
'id' => '22'
)
)
),
)
);
The code I've done so far is:
foreach($array as $devp => $dev){
foreach($dev as $comp => $com){
if($comp == null){
unset($array[$devp][$comp]);
}
}
}
But it's not working. I declared this condition ($comp == null) as comparing If $comp is equal to null. It should unset the array. What am I missing please help me.
In PHP null is a special datatype. And your key with value 'null' is a string.
So proper comparison is:
if ($comp == 'null') { // see quotes?
// do something
}

Why does this return a string value when there is no such index in the array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strange behavior with isset() returning true for an Array Key that does NOT exist
$arr = array(
'application' => array (
'environment' => 'development',
'mode_debug' => 1,
'key' => '123456abcdefg',
'debug_soft' =>
'firephp',
'aaa' => array (
'bbb' => '111',
'ccc' => '222',
'ddd' => array (
'eee' => '12345',
),
),
),
'database' => array (
'host' => 'localhost',
'database' => '',
'username' => '',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
),
);
if(isset($arr["application"]["aaa"]["ddd"]["eee"]['out']) && !empty($arr["application"]["aaa"]["ddd"]["eee"]['out'])){
echo "a";
echo '<br />';
var_dump($arr["application"]["aaa"]["ddd"]["eee"]['out']);
}else{
echo "b";
}
returns:
a
string(1) "1"
but there is no 'out' index in the '$arr' array, so why it returns 'string(1) "1"'?
The manual doesn't help, because it only samples one dimentional array:
$a = array ('test' => 1, 'hello' => NULL);
var_dump( isset ($a['test']) ); // TRUE
var_dump( isset ($a['foo']) ); // FALSE
var_dump( isset ($a['hello']) ); // FALSE
Consider this:
$str = 'test';
var_dump(isset($str['xxx'])); // true
It returns true, because:
PHP supports $str[$n] syntax (to address individual characters of the string)
when calculating index, it's cast to integer type
when cast to integer, "xxx" is 0; you're accessing $str[0] - the first character of that $str string, and it (t) is a truthy value.
Note that this (quite weird) behavior of isset was fixed in PHP 5.4:
5.4.0: Checking non-numeric offsets of strings now returns FALSE.
It does this because your eee index contains a string for a value - and strings can be accessed as arrays. When you use the index out in the string, it casts out to an integer value of 0, giving you $arr["application"]["aaa"]["ddd"]["eee"][0], which equals 1.
You can prevent this by using is_array():
if (is_array($arr["application"]["aaa"]["ddd"]["eee"]) && isset($arr["application"]["aaa"]["ddd"]["eee"]['out'])) {
It seems to return the first character '1' of $arr["application"]["aaa"]["ddd"]["eee"] value "12345" even key 'out' is not exist.

Add some logic in array filing

I'm trying to fill an array and I want to add some logic in it so it won't give me back errors...
Here is the code:
$entries_mixes = array();
foreach ($entries_query->result_array() as $entry) {
$entries_mixes[] = array('title' => $entry['title'],
'body' => $entry['body'],
'author' => $entry['author'],
'date_time' => $entry['date_time'],
'id' => $entry['id'],
'mix_name' => $mix['name'],
'photo_name' =>$photo['name']
);
}
what I want to do is to be able to check if some of the variables exist before I put them into the array....
so for example if(isset($mix['name'])) then insert to array or else do nothing
The point is not having undeclared variables trying to be inserted to my array cause it gives back errors...thanks!
You can use the ? : ternary operator:
$entries_mixes[] = array(
'title' => (isset($entry['title']) ? $entry['title'] : null),
'author' => (isset($entry['author']) ? $entry['author'] : null),
...
alternatively, use empty() for the check
You could use the ternary operator so that if the variables don't exist, NULL is used as the value. But you actually want to omit certain keys from the array altogether in that case. So just set each key separately:
$entry[] = array();
...
if (isset($mix['name'])) {
$entry['mix_name'] = $mix['name'];
}
...
$entries_mixes[] = $entry;
The following will check if title doesn't exists in the entry array or if it's blank. If so, it'll skip the entry completely and continue to the next element in the loop.
$entries_mixes = array();
foreach ($entries_query->result_array() as $entry) {
if (empty($entry['title'])) {
continue;
}
$entries_mixes[] = array('title' => $entry['title'],
'body' => $entry['body'],
'author' => $entry['author'],
'date_time' => $entry['date_time'],
'id' => $entry['id'],
'mix_name' => $mix['name'],
'photo_name' =>$photo['name']
);
}

Categories