1. Code
  2. Coding Fundamentals
  3. Machine Learning

Tips for Effective Code-Generating ChatGPT Prompt Design

Scroll to top

ChatGPT can be a great tool to boost your productivity. However, just like any other tool, the results you get back will depend on how adept you are at using it.

ChatGPT is very good at generating text. This doesn't include just regular text but also actual valid code that you can run. As a programmer, you can use ChatGPT to write a lot more code in less time.

In this tutorial, I will show how to write prompts effectively so that ChatGPT can generate accurate code for you. Before we begin, you should know that generating code with ChatGPT or any other AI has its pros and cons.

Make Your Prompts as Specific as Possible

I am sure that as a developer, you have come across people who make vague requests regarding what they want you to implement. For example, let's say someone asks you to build a website for a real estate company. The request might look specific enough to a non-developer. However, there are still a lot of things that you will need to ask the client. The more details they give you about the website, the better.

The same thing applies to ChatGPT. You have to make sure that your request is as specific as possible.

Let's say your goal is to create a PHP function that returns the product of all numbers in an array. The numbers might be arbitrarily large.

Here is an example of a non-specific prompt:

1
Write a function that calculates the product of all numbers in an array.

I told ChatGPT that I want a function that can calculate the product of all numbers. However, I didn't specify the language or that the numbers can be arbitrarily large. In this case, the output is a Python function to calculate the product.

1
def product_of_array(arr):
2
    if len(arr) == 0:
3
        return 0
4
5
    result = 1
6
    for num in arr:
7
        result *= num
8
    return result

Specify Your Programming Language in the Prompt

The above function is useless for us because we want something that is valid PHP. Here is a more specific prompt that specifies the language for our function:

1
Write a PHP function that calculates the product of all numbers in an array.

This might give you the following output:

1
<?php
2
3
function product_of_array($arr) {
4
    if (empty($arr)) {
5
        return 0;
6
    }
7
    
8
    return array_product($arr);
9
}
10
11
?>

As you can see, ChatGPT took advantage of the built-in array_product() function. The check for an empty array is necessary because array_product() returns 1 by default.

Be Specific About Other Requirements

The function from the previous section still won't work for arbitrarily large numbers. However, the prompt below should generate the desired function:

1
Write a PHP function that calculates the product of all numbers in an array.
2
The numbers can be arbitrarily large.
3
Take advantage of the built-in functions.

Here is the output that I received:

1
<?php
2
3
function product_of_array($arr) {
4
    return array_reduce($arr, function ($carry, $num) {
5
        return bcmul($carry, $num);
6
    }, '1');
7
}
8
9
?>

I passed an array of some very large numbers to this function, and it works as expected:

1
<?php
2
3
$numbers = ['9348716178971987', '58971298352986129862', '2140971429042398623', '53986234986149861298'];
4
$product = product_of_array($numbers);
5
6
// Output: 63721586073036849457435248171169202825849639897513248191471414837279417276

7
echo $product;
8
9
?>

Write Prompts That Break Down Complex Tasks Into Smaller Parts

You probably already know that it is a good programming practice to write functions that handle one specific task. This has several advantages. For instance, this will make your code modular and reusable. It will also improve the readability and maintainability of the code.

Consider the following prompt:

1
Write a PHP function to calculate the mean, median, mode and standard deviation of an array of numbers.

This time, we have specified our language of choice and also mentioned that we want to calculate four different things. With the above prompt, ChatGPT gave the following output in my case:

1
<?php
2
3
function calculate_statistics($arr) {
4
    $count = count($arr);
5
    $mean = array_sum($arr) / $count;
6
    
7
    sort($arr);
8
    $middle = floor(($count - 1) / 2);
9
    $median = $arr[$middle];
10
11
    $mode = array_count_values($arr);
12
    $mode = array_keys($mode, max($mode));
13
14
    $sumOfSquares = 0;
15
    foreach ($arr as $num) {
16
        $sumOfSquares += pow($num - $mean, 2);
17
    }
18
    $variance = $sumOfSquares / $count;
19
    $standardDeviation = sqrt($variance);
20
21
    return [
22
        'mean' => $mean,
23
        'median' => $median,
24
        'mode' => $mode,
25
        'standardDeviation' => $standardDeviation,
26
    ];
27
}
28
29
?>

This function does exactly what you want it to do. However, it isn't very modular. What if some other part of your code just requires the mean of all the numbers in an array?

You could make a call to calculate_statistics() and then extract the mean from the returned array. However, that is a lot of overhead. A better approach would be to ask ChatGPT to generate separate functions to calculate the mean, median, mode, and standard deviation.

You can do so by specifically asking ChatGPT to define separate functions for all these tasks:

1
Write separate PHP functions to calculate the mean, median, mode and standard deviation of an array of numbers.

In this case, the output looks like:

1
<?php
2
3
function calculate_mean($arr) {
4
    $sum = array_sum($arr);
5
    $count = count($arr);
6
    return $sum / $count;
7
}
8
9
10
function calculate_mode($arr) {
11
    $counts = array_count_values($arr);
12
    $maxCount = max($counts);
13
    $mode = array_keys($counts, $maxCount);
14
15
    return $mode;
16
}
17
18
// .. and other functions.

19
20
?>

On a similar note, you can't prompt ChatGPT to write code for creating a social network or implementing a comment system. It might give you back some code for common things such as a to-do list, but the code will be pretty generic. You will have to break down the original task into smaller steps to get a to-do list manager tailored to your requirements.

Prompts Should Mention Constraints and Edge Cases

Code that you write in real life usually requires to you deal with constraints and handle any edge cases. When giving ChatGPT prompts to write a function, make sure that you mention those constraints and edge cases.

Let's say you want a PHP function that can transform any given string so that it is in title case. The prompt to do so is very simple, as shown below:

1
Write a PHP function to convert a string to title case.

This gives me the following output:

1
function convert_to_title_case($str) {
2
    return ucwords(strtolower($str));
3
}

Pass a sentence to this function, and you will see that it capitalizes the first letter of all the words. Here is an example:

1
<?php
2
3
// Output: How To Add And Remove Event Listeners In Javascript

4
echo convert_to_title_case("How to add and remove event listeners in JavaScript");
5
6
?>

If you want to leave out some two-letter or three-letter words, you should update your prompt to do so.

1
Write a PHP function to convert a string to title case.
2
Don't capitalize any two letter words.
3
Also, don't capitalize the words "a, and".

Once you mention these constraints, the function definition changes to include the constraints:

1
<?php
2
3
function convert_to_title_case($str) {
4
    $excludedWords = array('a', 'and');
5
    
6
    $words = explode(' ', strtolower($str));
7
    
8
    $titleCaseWords = array_map(function($word) use ($excludedWords) {
9
        if (in_array($word, $excludedWords) || strlen($word) === 2) {
10
            return $word;
11
        } else {
12
            return ucfirst($word);
13
        }
14
    }, $words);
15
    
16
    return implode(' ', $titleCaseWords);
17
}
18
19
// Output: How to Add and Remove Event Listeners in Javascript

20
echo convert_to_title_case("How to add and remove event listeners in JavaScript");
21
22
?>

Keep Testing the Code and Refining the Prompts

It is a good idea to have some sample data handy that you can use to test the code that ChatGPT gives you. You can also provide some of this sample input and output data to ChatGPT beforehand so that it knows what you expect any code that it writes to do.

For simple instructions, the code you get from ChatGPT will work as expected. However, that might not always be the case. In those situations, you will have to keep updating the prompt until it does exactly what you want it to do.

People who are paying close attention might have noticed that the function in the previous example changed JavaScript to Javascript. This is an unintended consequence, and we want to avoid this in the next iteration of the function. Therefore, we simply add another instruction to the prompt.

1
Write a PHP function to convert a string to title case. Follow these rules:
2
3
1. Only change the case of the first letter in each word. Leave all other letters unchanged.
4
2. Don't capitalize any two letter words.
5
3. Also, don't capitalize the words "a, and".

The function that we get back now will not change the case of any letters except the first one.

Final Thoughts

In this tutorial, we learned how to use ChatGPT to generate code in PHP. The key to generating useful code with ChatGPT is to be very clear with your instructions. Every now and then, the code you get back might not work as intended. In those situations, you can either update the prompt or ask ChatGPT for an explanation of the code it has written.

Asking ChatGPT for an explanation is a great way to refine the generated code. You can also ask ChatGPT to use a different approach to solve your problems. For example, I asked ChatGPT for an alternative way to convert sentences to title case, and it generated a new function that used regular expressions. You can then weigh the pros and cons of using these different techniques.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.