简体   繁体   中英

How can I simplify this function - return key value from array?

I have written the following function which returns the value of a key which is the account prefix of a cPanel account. [prefix] = 'oneclick_'

The function works but I'm only a beginner and I'm sure there's an easier and better way to write this function.

<?php
// Get data from cPanel API
$array = $cp_db_restrictions['cpanelresult']['result']['data'];

//Pass array of $data to function
db_prefix( $array );

//Function accepts array of $data
function db_prefix( $array ) {
  if( count( $array ) > 0 ) {
      return $array['prefix'];
  } else {
      return "No prefix";
  }
}
?>

<?php echo db_prefix($array); ?>

The function echos "oneclick_"

EDIT: This is the code which returns the array:

$cp_db_restrictions = $cpanel->uapi(
      'Mysql', 'get_restrictions'
  );

However, I'm not quite sure how to add that into the function. When I try I get the following error message:

Notice: Undefined variable: array in...

Fatal error: Uncaught Error: Call to a member function uapi() on null in...

SOLUTION*

So, thanks to Nick's answer here is the solution. You must make sure to declare the cPanel class at the top of the document and within the same PHP tags.

<?php
include("/usr/local/cpanel/php/cpanel.php"); // Instantiate the CPANEL object.
$cpanel = new CPANEL();

function db_prefix($cpanel) {
      $cp_db_restrictions = $cpanel->uapi('Mysql', 'get_restrictions');
      $array = $cp_db_restrictions['cpanelresult']['result']['data'];
      return $array['prefix'] ?? 'No prefix';
} ?>
<?php echo db_prefix($cpanel); ?>

In PHP7 you can just use the null coalescing operator ?? :

echo $array['prefix'] ?? 'No prefix';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM