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!).

Functions that i find handy in 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']