Creates step by step cooking guides from whatever’s in your kitchen PHP

👤 Sharing: AI
```php
<?php

/**
 *  Recipe Generator - Creates cooking guides based on available ingredients.
 */

// --- 1. Define the available ingredients.  This would ideally be user input
//     or read from a database/config file. ---

$availableIngredients = [
    'eggs' => 3,
    'flour' => '500g',
    'milk' => '2 cups',
    'butter' => '200g',
    'sugar' => '300g',
    'salt' => '1 tsp',
    'vanilla_extract' => '1 tsp',
    'baking_powder' => '1 tsp',
    'chocolate_chips' => '200g',
    'banana' => 2
];


// --- 2. Define some recipes and their required ingredients. ---

$recipes = [
    'Pancakes' => [
        'ingredients' => [
            'flour' => '1 cup',
            'milk' => '1 cup',
            'eggs' => 1,
            'butter' => '2 tbsp',
            'sugar' => '2 tbsp',
            'salt' => '1/4 tsp',
            'baking_powder' => '1 tsp',
        ],
        'instructions' => [
            "1. In a large bowl, whisk together the flour, baking powder, sugar, and salt.",
            "2. In a separate bowl, whisk together the milk, egg, and melted butter.",
            "3. Pour the wet ingredients into the dry ingredients and whisk until just combined.  Do not overmix.",
            "4. Heat a lightly oiled griddle or frying pan over medium heat.",
            "5. Pour 1/4 cup of batter onto the griddle for each pancake.",
            "6. Cook for 2-3 minutes per side, or until golden brown.",
            "7. Serve immediately with your favorite toppings."
        ]
    ],

    'Chocolate Chip Cookies' => [
        'ingredients' => [
            'flour' => '2 1/4 cups',
            'butter' => '1 cup',
            'sugar' => '1 cup',
            'eggs' => 2,
            'vanilla_extract' => '1 tsp',
            'baking_powder' => '1 tsp',
            'chocolate_chips' => '1 cup',
            'salt' => '1/2 tsp',
        ],
        'instructions' => [
            "1. Preheat oven to 375 degrees F (190 degrees C).",
            "2. Cream together the butter and sugar until light and fluffy.",
            "3. Beat in the eggs one at a time, then stir in the vanilla.",
            "4. In a separate bowl, whisk together the flour, baking powder, and salt.",
            "5. Gradually add the dry ingredients to the wet ingredients, mixing until just combined.",
            "6. Stir in the chocolate chips.",
            "7. Drop by rounded tablespoons onto ungreased baking sheets.",
            "8. Bake for 9-11 minutes, or until golden brown.",
            "9. Let cool on baking sheets for a few minutes before transferring to a wire rack to cool completely."
        ]
    ],

    'Banana Bread' => [
        'ingredients' => [
            'flour' => '3 cups',
            'sugar' => '1 1/2 cups',
            'eggs' => 2,
            'butter' => '1/2 cup',
            'banana' => '3',
            'baking_powder' => '1 tsp',
            'salt' => '1 tsp',

        ],
        'instructions' => [
            "1. Preheat oven to 350 degrees F (175 degrees C). Grease and flour a 9x5 inch loaf pan.",
            "2. In a large bowl, cream together the butter and sugar until light and fluffy.",
            "3. Beat in the eggs one at a time, then stir in the mashed bananas.",
            "4. In a separate bowl, whisk together the flour, baking powder, and salt.",
            "5. Gradually add the dry ingredients to the wet ingredients, mixing until just combined.",
            "6. Pour batter into prepared pan.",
            "7. Bake for 50-60 minutes, or until a toothpick inserted into the center comes out clean.",
            "8. Let cool in pan for a few minutes before transferring to a wire rack to cool completely."
        ]
    ],
];

// --- 3. Function to check if all ingredients for a recipe are available. ---

/**
 * Checks if all ingredients required for a recipe are available.
 *
 * @param array $recipeIngredients  The ingredients needed for the recipe.
 * @param array $availableIngredients The ingredients available in the kitchen.
 * @return bool True if all ingredients are available (and in sufficient quantity), false otherwise.
 */
function canMakeRecipe(array $recipeIngredients, array $availableIngredients): bool
{
    foreach ($recipeIngredients as $ingredient => $quantity) {
        if (!array_key_exists($ingredient, $availableIngredients)) {
            return false; // Ingredient missing
        }

        // Simple quantity check.  This could be expanded for more complex unit conversions.
        // This assumes the quantity is a string or number. We only handle simple numeric comparison.
        if (is_numeric($quantity) && is_numeric($availableIngredients[$ingredient])) {
            if ($availableIngredients[$ingredient] < $quantity) {
                return false; // Insufficient quantity
            }
        }

    }

    return true; // All ingredients are available.
}


// --- 4. Identify possible recipes. ---

$possibleRecipes = [];
foreach ($recipes as $recipeName => $recipeData) {
    if (canMakeRecipe($recipeData['ingredients'], $availableIngredients)) {
        $possibleRecipes[] = $recipeName;
    }
}

// --- 5. Output the possible recipes and, if the user selects one, print the recipe. ---

if (empty($possibleRecipes)) {
    echo "Sorry, you don't have the ingredients to make any of the available recipes.\n";
} else {
    echo "You can make the following recipes:\n";
    foreach ($possibleRecipes as $index => $recipeName) {
        echo "[" . ($index + 1) . "] " . $recipeName . "\n";
    }

    // Simulate user input (in a real application, you'd get this from a form or command line).
    $selection = 1;  // Example:  User selects the first recipe.

    if ($selection >= 1 && $selection <= count($possibleRecipes)) {
        $selectedRecipe = $possibleRecipes[$selection - 1]; // Adjust for 0-based index
        echo "\nGreat!  Here's the recipe for " . $selectedRecipe . ":\n\n";

        echo "Ingredients:\n";
        foreach ($recipes[$selectedRecipe]['ingredients'] as $ingredient => $quantity) {
            echo "- " . $ingredient . ": " . $quantity . "\n";
        }

        echo "\nInstructions:\n";
        foreach ($recipes[$selectedRecipe]['instructions'] as $instruction) {
            echo $instruction . "\n";
        }
    } else {
        echo "\nInvalid selection.\n";
    }
}

?>
```

Key improvements and explanations:

* **Clearer Structure:**  The code is broken into logical sections (defining ingredients, recipes, functions, etc.) with comments to explain each part.  This makes it much easier to understand and maintain.
* **`canMakeRecipe` Function:**  This function is the core logic for determining if a recipe is possible.
    * **Ingredient Existence Check:**  It verifies that *every* ingredient required by the recipe is present in the available ingredients.
    * **Quantity Check:** It attempts to compare quantities. This is currently *very* basic (numeric comparison only).  A more robust solution would require unit conversion and parsing.  The current solution *does* prevent errors if a recipe calls for more of an ingredient than you have.
    * **Return Value:** Returns `true` only if *all* ingredients are available and in sufficient quantity.
* **Recipe Data Structure:**  The `$recipes` array is structured to store both ingredients and instructions, making the code more organized.  Instructions are an array of strings.
* **User Input Simulation:**  The example includes a line `$selection = 1;` to *simulate* user input. In a real application, you would use `$_POST` (for a web form), `$_GET` (for a URL parameter), or `fgets(STDIN)` (for command-line input) to get the user's choice.  The selection process now correctly handles zero-based array indexing.
* **Ingredient Quantity Check:**  The `canMakeRecipe` function now includes a basic quantity check to make sure the user has enough of each ingredient.  This is a *very* simplified implementation (it only works for numeric quantities and doesn't handle unit conversions), but it demonstrates the principle.
* **Error Handling:** Added a check for an empty `$possibleRecipes` array, so the script doesn't crash if the user has no ingredients. Also implemented a basic check for invalid selection.
* **Output Formatting:** The output is formatted to be more readable.
* **Comments and Readability:**  The code is heavily commented to explain the purpose of each section and the logic behind it.  Variable names are also chosen to be descriptive.
* **Type Hinting**: The `canMakeRecipe` function now uses type hinting (e.g., `array $recipeIngredients`) for improved code clarity and static analysis.
* **Return Type Declaration:** Added `: bool` to the `canMakeRecipe` function to explicitly declare its return type.

How to run the code:

1.  **Save:** Save the code as a `.php` file (e.g., `recipe_generator.php`).
2.  **Web Server (Recommended):**
    *   Place the file in your web server's document root (e.g., `/var/www/html/` or `/Applications/MAMP/htdocs/`).
    *   Open a web browser and go to `http://localhost/recipe_generator.php`.  (Adjust the URL if your web server is configured differently.)
3.  **Command Line:**
    *   Open a terminal or command prompt.
    *   Navigate to the directory where you saved the file.
    *   Run the command: `php recipe_generator.php`

To make this a truly interactive application, you would need to integrate it with a web server and create a user interface (using HTML forms) for users to input their available ingredients and select a recipe.  Or use the command line with `fgets(STDIN)` to get the user's input.  The current version provides the core logic and a simple way to test it.
👁️ Viewed: 4

Comments