Development

PHP all about functions

PHP functions, a very simple way to prevent repetitive code and save you time.

An example of a PHP function:

function test($a, $b){
  $var = $a + $b;
  return $var;    
}

echo test('10', '30');//40
echo test('22', '14');//36

Here we made or defined a function called test which has two inputs variable a and b. Inside the function we have a variable var that is what a + b equals. This is then returned. Note that all functions must have a return, the return can be empty though. The function test can be called, echo’d of assign to a variable and as you see from the 2 example echos using functions is a space saver (and this is only a mini simple function!).

PHP 7.4 brings type declarations:

function footerText(string $text, int $year)
{
    return "$text. copyright $year";
}

As well as return type hints:

function doCalc(int $start, int $finish): int
{
    return ($start * ($start + $finish));
}

Functions that I find handy with API calls are ones that return arrays. That way you can make just one API call and store several bits of data in an array rather than doing multiple calls and using up your api limits.

//Array function
function array($id, $api_key){
$data = json_decode(file_get_contents("https://exampleapicall.com/profiles&id=".$id."&key=".$api_key.""),true);
$name = $data->name;
$email = $data->email;
$score = $data->score;
$joined = $data->joined;
 return array('name' => $name, 'email' => $email, 'score' => $score, 'joined' => $joined);
}
$jims_data = array('1952', '4678hcxhjg6d78fyh');
echo $jims_data['name'];//Jim
echo $jims_data['score'];//1138

$jims_name = $jims_data['name']//asigns jims name to a variable

Here the function requires the id of the profile we want to query and the API key. We then pack what we need from the JSON into an array to store. When we need to access jims data we just call $jims_data['KEY']

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago