Improving script

Hello there,
Expecting some advice not a big deal though.

I wrote a little script to extract words out of a list of items and
print back (echo) whether they are ‘singular’ or ‘plural’ by calculating number of items and adding an ‘s’ to the end of the noun if it was plural. here is the code. also this is for a practicing.

<?php

$pets = array('cat' => 3, 
                'dog' => 5, 
                'goat' => 4, 
                'sheep' => 0, 
                'cow' => 1,
                'pig' => 2,
                'Rooster'=> 10,
                'Hen' => 5);
                
  $makeNounplural = 's';              
                
  foreach($pets as $value => $amount) {
  if ($amount > 1 ) { 
       echo $amount . ' ' . ucwords($value).$makeNounplural , "\n";
    } else if ($amount == 1 || $amount < 0) {
       echo $amount . ' ' . ucwords($value), "\n";
    } 
  } //end of foreach loop  
  
  $newVal = array_sum($pets);
    echo "There are ", $newVal, " total pets";
  
?>

How can I improve this further for a real application?

Thank you.

What you have here will work. There’s nothing really wrong with it per sey.

Since you are iterating over the array, you might want to look at PHP: array_walk - Manual instead as this will at least push the loop into the engine. (It will be faster)

and of course, I’d make a class out of it and make this a method of the class. Hand in the array, do the loop and generate a new array of responses and return the responses. Then you can just iterate over that array and echo it out.

Again, these are not necessarily the “right” way to do it, it’s just the way I would refactor. Lacking context of how this would be used, that’s all the suggestions I have. :slight_smile:

Cheers!
=C=

1 Like

Thank you for your suggestions and for the help. i highly appreciate it. and, i am still learning myself web development so, this kind of suggestions comes in handy.

1 Like