We’ve all been either introduced to or have heard about OpenAI’s platform ChatGPT; the seemingly powerful and really fun (or scary) AI system that can do anything. From generating a short novel based on any prompt you give it, or whipping up never before seen photos created from the most imaginative descriptions possible. But did you know it could also help you write code and find solutions to programming problems?
It’s true! You can ask ChatGPT to “write me a ‘Hello World’ script, in PHP, and capitalize ‘world’” and it will simply generate code to do that! Of course, you can feed it more difficult questions and scenarios, but with a careful eye and great attention to detail, you CAN utilize the platform to handle the mundane tasks and boilerplate code.
“The most efficient developers aren’t remembering everything from memory, they are using the tools around them to be resourceful.”
Simple ChatGPT Example
Let’s generate a simple block of code in my favorite language, PHP. We’ll keep the controls simple and use the default:
- Model = text-davinci-003 (the best quality model for text generation)
- Temperature = 0.7 (the lower, the more verbose and predictable the output should be) *Maximum Length = 246 (reasonable for this simple task)
- The rest of the controls don’t necessarily affect the output of a simple task like this.
The prompt source is the following:
Coding Langauge: PHP
Generate me a script that can take an array of items and remove any duplicates. The array should contain the following items
- Apple
- Car
- Coffe
- Horse
- Car
- Desk
- Laptop
- A rubber duck
And then we have the script it generated:
<?php
$items = array("Apple", "Car", "Coffee", "Horse", "Car", "Desk", "Laptop", "A rubber duck");
$unique_items = array_unique($items);
print_r($unique_items);
?>
Looks pretty good to me! As someone competent and very knowledgeable with PHP, I can quickly tell it what I want, and then do a code review to ensure the output is both safe and does what I want.
Of course in this simple example, it’s easy to catch mistakes or issues. But the idea is to promote the usefulness of ChatGPT quickly, and nearly instantly generating the block of code we need.
Set it & Forget it?
No. This isn’t a tool that will magically handle all of your tasks, code writing, or day planning. It can and does fall short in plenty of areas. In the context of code generation, you have to ensure the output is reasonable and actually performs the task being input. This is the part that is extremely important to using it effectively, and to improve your efficiency; it DOES require oversight and reviews.
Let’s get complex
Sure, the above simple example is easy to dismiss as “duh,” of course it can do it, and output a working set of code instructions. What if we ask it to do something beyond generating code? What if we present a real world problem, ask for a breakdown of the code, and then make some personal adjustments?
Prompt source:
Coding Langauge: PHP
I need to sort a one column CSV file with 100 records full of IP Address. I need to see which IP address shows up the most and have the code explained to me, please.
The source from the output:
The following code can be used to sort a one-column CSV file with 100 records full of IP addresses.
<?php
//open the CSV file
$file = fopen("file.csv","r");
//initialize an array to store the IP addresses
$ips = array();
//read each line of the file
while(!feof($file)){
//read the line
$line = fgets($file);
//if the line is not blank
if($line !== ""){
//add the IP address to the array
$ips[] = $line;
}
}
//close the file
fclose($file);
//sort the IP addresses by frequency
$ips_by_frequency = array_count_values($ips);
//sort the IP addresses by frequency in descending order
arsort($ips_by_frequency);
//output the most frequent IP address
echo "The most frequent IP address is: " . key($ips_by_frequency);
?>
The code first opens the CSV file. Then, it initializes an array to store the IP addresses. It then reads each line of the file and adds the IP address to the array. Finally, it sorts the IP addresses by frequency, in descending order, and outputs the most frequent IP address.
Pretty impressive right? It seems like all of the code is there, just copy and paste and… wait…
If you actually pasted the above into a file, it’s going to look odd or error out. The text outside of the PHP opening/closing tags doesn’t feel right. At best, include those comments inside of the opening/closing tags in comment form.
A personal choice, is the usage of snake-case variables. I prefer camel-case. So how could we adjust? While we didn’t initially tell it to utilize camel-case, we can simply inject the following into the prompt source:
I need camel-case variables.
And of course, it adjusted the naming conventions to use camel-case:
Here is some code to sort a one column CSV file with 100 records that contain IP Addresses and count how many times each IP Address appears:
<?php
//Set path to CSV file
$csvFilePath = 'example.csv';
//Open CSV file
$csvFile = fopen($csvFilePath, 'r');
//Initialize a variable to hold counts of IP Addresses
$ipAddressCounts = array();
//Loop through CSV file
while (($line = fgetcsv($csvFile)) !== FALSE)
{
//Get IP Address from each line of CSV file
$ipAddress = $line[0];
//Check if IP Address exists in array
if(array_key_exists($ipAddress, $ipAddressCounts))
{
//Increment count for existing IP Address
$ipAddressCounts[$ipAddress] += 1;
}
else
{
//Set count for new IP Address
$ipAddressCounts[$ipAddress] = 1;
}
}
//Close CSV file
fclose($csvFile);
//Print out IP Addresses and counts
foreach($ipAddressCounts as $ipAddress => $count)
{
echo "$ipAddress: $count\n";
}
?>
We can see it is fairly different code than before, just based off of a simple additional sentence. The code above is a bit lazier, and simply outputs all of the IP Addresses with a count; it doesn’t just output the most repeated IP Address like I asked. While an additional personal choice, it also places open and closing logic brackets on new lines, something I’m not a fan of for basic logic exercises.
This is a great example of our instructions seeming to be okay, but we’ll now need to make some adjustments. Regardless, this got us pretty close and saved us quite some time. Especially true for the slower coders among us.
Final Thoughts
Why did I ask it please? For when the inevitable happens and the machines take over our jobs and world. All jokes aside, these tools aren’t taking away our jobs anytime soon. We should learn to work alongside them in bettering ourselves, our productivity, and lean on them to empower our skills and abilities whenever possible!
Top comments (0)