Not very strong in PHP so here is my question:
I am building a simple array to return as json, populating it with data from another array. The $eventarray may have the index gas or may not so I need to check for existing gas index and if it exist get the value if not populate with a default value.
How would I do that the most optimal way?
Again not that strong in PHP.
Here is the array:
$somearr = array(
"actiontaken"=>sprintf("%s", $eventarray['desc']),
"actionname" =>sprintf("%s", $eventarray['name']),
"type" =>sprintf("%s", $eventarray['type']),
"subtype" =>sprintf("%s", $eventarray['name']),
"min" =>sprintf("%s", $eventarray['min']),
"gas" =>sprintf("%s", $eventarray['gas']),
"playerId"=>$value['p'],
"name" =>$value2['name'],
"race" =>$value2['race']
);
You can use isset()
to check if the element exists (and is not null
):
isset($eventarray['gas']) ? $eventarray['gas'] : 'defaultvalue'
Note: In case null
is a possible value where you do not want the default value to be used you cannot use isset
but have to use array_key_exists($eventarray, 'gas')
instead.
use this
array_key_exists('gas', $somearr);
You could use a ternary operator to check for its existence, and set a default value.
The way it works is: ( condition ) ? [if true] : [ if false]
...
"gas" => (isset($eventarray['gas'])) ? $eventarray['gas'] : 'default',
Initialise your $somearr array first with default values:
$somearr = array(
'actiontaken' => 'default action',
'actionname' => 'default action name',
etc.. );
Then loop through $eventarray:
foreach( $eventarray as $event => $eventval ) {
$somearr[$event] = $eventval;
}
Use ternary operator:
"actiontaken"=>sprintf("%s", (isset($eventarray['desc']) && !empty($eventarray['desc'])) ?$eventarray['desc'] : 'Default Value'),