Jump to content

Function in php


Serigne
Go to solution Solved by Barand,

Recommended Posts

Hello I have a little problem with this exercise I managed to access the elements of the arrays but I can't display the results for: 

echo "Expression 1 evaluates to: " . evaluate($expression1) . " <br>";
echo "Expression 2 evaluates to: " . evaluate($expression2) . " <br>";
echo "Expression 3 evaluates to: " . evaluate($expression3) . " <br>";

Need help please

 

<?php

function evaluate($expression){
    // TODO : add rendering code here
    
    $test0 = $expression['children'][0]['value'];
    $test1 = $expression['children'][1]['value'];
    $test2 = $expression['children'][2]['value'];
    return $test0+$test1+$test2;
    $exp = $expression['children'][0]['value'];
    $exp1 = $expression['children'][1]['children'][0]['value'];
    $exp2 = $expression['children'][1]['children'][1]['children'][0]['value'];
    $exp3 = $expression['children'][1]['children'][1]['children'][1]['value'];
    return ($exp+$exp1 * ($exp2 + $exp3));
    $resp = $expression['children'][0]['value'];
    $resp1 = $expression['children'][1]['top']['value'];
    $resp2 = $expression['children'][1]['bottom']['value'];

    return $resp + $resp1 / $resp2;

}

// 100 + 200 + 300
$expression1 = [
    "type" => "add",
    'children'=> [
        [
            "type" => "number",
            "value"=>100
        ],
        [
            "type" => "number",
            "value"=> 200
        ],
        [
            "type" => "number",
            "value"=> 300
        ]
    ]
];
$expression2 = [
        "type" => "add",
        'children'=> [
                [
                        "type" => "number",
                        "value"=>100
                ],
                [
                        "type" => "multiply",
                        "children" =>[
                                [
                                        "type" => "number",
                                        "value"=>2
                                ],
                                [
                                        "type" => "add",
                                        "children" =>[
                                            [
                                                "type" => "number",
                                                "value"=>5
                                            ],
                                            [
                                                "type" => "number",
                                                "value"=>45
                                            ]
                        ]
                                ]
                        ]
                ]
        ]
];
$expression3 = [
    "type" => "add",
    'children'=> [
        [
            "type" => "number",
            "value"=>1
        ], 
        [
            "type" => "fraction",
            "top"=>
                [
                    "type" => "number",
                    "value"=>100
                ],
            "bottom"=>
                [
                    "type" => "number",
                    "value"=>1000
                ]
        ]
    ]
];
echo "Expression 1 evaluates to: " . evaluate($expression1) . " <br>";
echo "Expression 2 evaluates to: " . evaluate($expression2) . " <br>";
echo "Expression 3 evaluates to: " . evaluate($expression3) . " <br>";

 

Link to comment
Share on other sites

An echo statement sends data to the client screen usually.  A function, given a set of arguments to work with, does something for you and literally returns a result in a certain format to the calling code.  That mainline code then continues on with that value(s) where it may be used further or actually output, using an echo perhaps.

Link to comment
Share on other sites

The exrcise is here:

 Implement the 'evaluate()' function in the following program to calculate the result of
arbitrary expressions, such as the ones provided in file exercice-1.php. Output will look
like this :

<?php

function evaluate($expression){
    // TODO : add rendering code here
    
    

}

// 100 + 200 + 300
$expression1 = [
    "type" => "add",
    'children'=> [
        [
            "type" => "number",
            "value"=>100
        ],
        [
            "type" => "number",
            "value"=> 200
        ],
        [
            "type" => "number",
            "value"=> 300
        ]
    ]
];
$expression2 = [
        "type" => "add",
        'children'=> [
                [
                        "type" => "number",
                        "value"=>100
                ],
                [
                        "type" => "multiply",
                        "children" =>[
                                [
                                        "type" => "number",
                                        "value"=>2
                                ],
                                [
                                        "type" => "add",
                                        "children" =>[
                                            [
                                                "type" => "number",
                                                "value"=>5
                                            ],
                                            [
                                                "type" => "number",
                                                "value"=>45
                                            ]
                        ]
                                ]
                        ]
                ]
        ]
];
$expression3 = [
    "type" => "add",
    'children'=> [
        [
            "type" => "number",
            "value"=>1
        ], 
        [
            "type" => "fraction",
            "top"=>
                [
                    "type" => "number",
                    "value"=>100
                ],
            "bottom"=>
                [
                    "type" => "number",
                    "value"=>1000
                ]
        ]
    ]
];
echo "Expression 1 evaluates to: " . evaluate($expression1) . " <br>";
echo "Expression 2 evaluates to: " . evaluate($expression2) . " <br>";
echo "Expression 3 evaluates to: " . evaluate($expression3) . " <br>";

 

27 minutes ago, ginerjm said:

An echo statement sends data to the client screen usually.  A function, given a set of arguments to work with, does something for you and literally returns a result in a certain format to the calling code.  That mainline code then continues on with that value(s) where it may be used further or actually output, using an echo perhaps.

 

Test de programmation 2021_page2_image6.jpg

Link to comment
Share on other sites

Ok - ran your code and you have a data structure problem.  Plus your function is FU.

You can only execute ONE return statement in a function.  As you have been told, once you return from a function that's it.

Your first expression data works just fine with your function, using the first return of course.

Your 2nd expression data is different than the first one.  You have a 'children' array inside of the 2nd children element which your first one does not have.  Your code fails when trying to navigate thru that data.

Here's what the script gives to me:  ( I have error checking turned on, hence the error message):

Expression 1:
Array
(
    [type] => add
    [children] => Array
        (
            [0] => Array
                (
                    [type] => number
                    [value] => 100
                )

            [1] => Array
                (
                    [type] => number
                    [value] => 200
                )

            [2] => Array
                (
                    [type] => number
                    [value] => 300
                )

        )

)
Expression 1 evaluates to: 600
Expression 2:
Array
(
    [type] => add
    [children] => Array
        (
            [0] => Array
                (
                    [type] => number
                    [value] => 100
                )

            [1] => Array
                (
                    [type] => multiply
                    [children] => Array
                        (
                            [0] => Array
                                (
                                    [type] => number
                                    [value] => 2
                                )

                            [1] => Array
                                (
                                    [type] => add
                                    [children] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [type] => number
                                                    [value] => 5
                                                )

                                            [1] => Array
                                                (
                                                    [type] => number
                                                    [value] => 45
                                                )

                                        )

                                )

                        )

                )

        )

)

Notice: Undefined index: value in /home/albany/public_html/homejg/test.php on line 95

Notice: Undefined offset: 2 in /home/albany/public_html/homejg/test.php on line 96

Notice: Trying to access array offset on value of type null in /home/albany/public_html/homejg/test.php on line 96
Expression 2 evaluates to: 100
Expression 3:
Array
(
    [type] => add
    [children] => Array
        (
            [0] => Array
                (
                    [type] => number
                    [value] => 1
                )

            [1] => Array
                (
                    [type] => fraction
                    [top] => Array
                        (
                            [type] => number
                            [value] => 100
                        )

                    [bottom] => Array
                        (
                            [type] => number
                            [value] => 1000
                        )

                )

        )

)

Notice: Undefined index: value in /home/albany/public_html/homejg/test.php on line 95

Notice: Undefined offset: 2 in /home/albany/public_html/homejg/test.php on line 96

Notice: Trying to access array offset on value of type null in /home/albany/public_html/homejg/test.php on line 96
Expression 3 evaluates to: 1

This is line 95:

  $test1 = $expression['children'][1]['value'];

 

Link to comment
Share on other sites

the nested data structures and the statement of 'arbitrary expressions' indicates that you are expected to write a recursive function to do this and since you wouldn't have been given this assignment without first having covered recursive functions, what information has been covered prior to this assignment?

Link to comment
Share on other sites

In addition to being recursive, your evaluate() function needs to be able to deal with each expression type and calculate thier results. Something like this to get you started (I've done the type='number' case for you)

function evaluate($exp)
{
    switch ($exp['type'])  {
        case 'number':
            $result = $exp['value'];
            break;
        case 'add':
            $result = ???;
            break;
        case 'multiply':
            $result = ???;
            break;
        case 'fraction':
            $result = ???
            break;
    }
    return $result;
}

 

Link to comment
Share on other sites

18 hours ago, Barand said:

In addition to being recursive, your evaluate() function needs to be able to deal with each expression type and calculate thier results. Something like this to get you started (I've done the type='number' case for you)

 

Thank's for your answer so for doing the same for add i use: $result = $exp['value']+$exp['value'] or i use $exp['children']['value']? I'm trying to resolve this function i just wont to improve my PHP. Just give me a incation for add please

 

Link to comment
Share on other sites

<?php

function evaluate($expression){
    // TODO : add rendering code here
    

    switch ($expression['type'])  {
        case 'number':
            $result = $expression['value'];
            break;
        case 'add':
            $result = 0;
            foreach ($expression['children'] as $child)  {
                $result += evaluate($child);
            }
            break;
        case 'multiply':
            $result = 1;
            foreach ($expression['children'] as $child)  {
                $result *= evaluate($child);
            }
            break;
        case 'fraction':
            $result = evaluate($expression['top']) / evaluate($expression['bottom']);
            break;
    }
    return $result;
}

    
    



// 100 + 200 + 300
$expression1 = [
    "type" => "add",
    'children'=> [
        [
            "type" => "number",
            "value"=>100
        ],
        [
            "type" => "number",
            "value"=> 200
        ],
        [
            "type" => "number",
            "value"=> 300
        ]
    ]
];
$expression2 = [
        "type" => "add",
        'children'=> [
                [
                        "type" => "number",
                        "value"=>100
                ],
                [
                        "type" => "multiply",
                        "children" =>[
                                [
                                        "type" => "number",
                                        "value"=>2
                                ],
                                [
                                        "type" => "add",
                                        "children" =>[
                                            [
                                                "type" => "number",
                                                "value"=>5
                                            ],
                                            [
                                                "type" => "number",
                                                "value"=>45
                                            ]
                        ]
                                ]
                        ]
                ]
        ]
];
$expression3 = [
    "type" => "add",
    'children'=> [
        [
            "type" => "number",
            "value"=>1
        ], 
        [
            "type" => "fraction",
            "top"=>
                [
                    "type" => "number",
                    "value"=>100
                ],
            "bottom"=>
                [
                    "type" => "number",
                    "value"=>1000
                ]
        ]
    ]
];
echo "Expression 1 evaluates to: " . evaluate($expression1) . " </br>";
echo "Expression 2 evaluates to: " . evaluate($expression2) . " <br>";
echo "Expression 3 evaluates to: " . evaluate($expression3) . " <br>";

Thank to all for your intervention and special thank to @Barand who help me for solution: here the code for  someone interesting 

Link to comment
Share on other sites

My full explanation...

Let's go right back to basics.

If you have an array of numbers

$arr = [ 100, 200, 300 ];

the to get the sum of those numbers you would start with a 0 total then loop through the array adding each of the numbers to the total.

$total = 0;
foreach ($arr as $num) {
    $total += $num;
}
echo $total;        // 600

$expression1 is a similar array but this time each item of the children array is an expression which has to be evaluated.

$expression1 = [
    "type" => "add",
    'children'=> [
        [
            "type" => "number",
            "value"=>100
        ],
        [
            "type" => "number",
            "value"=> 200
        ],
        [
            "type" => "number",
            "value"=> 300
        ]
    ]
];

So we start with a basic evaluate() function which knows how to evaluate a number experession and how to handle $expression1 (an add expression)...

function evaluate($exp)
{
    switch ($exp['type'])  {
        case 'number':
            $result = $exp['value'];
            break;
        case 'add':
            $result = 0;
            foreach ($exp['children'] as $child)  {
                $result += evaluate($child);
            }
            break;
    }
    return $result;
}

We can now call

echo evaluate($expression1);

This initial call to the function looks at the expression type and sees it is "add", so it sets the result to 0 and loops through the children to add each one to the result. To do this it has to call evaluate($child) for each one to get the number value to be added.

The multiply is very similar to the add except we must start with a result of 1 (otherwise we just multiply everything by 0, resulting in 0).

This is the full evalute() function...

function evaluate($exp)
{
    switch ($exp['type'])  {
        case 'number':
            $result = $exp['value'];
            break;
        case 'add':
            $result = 0;
            foreach ($exp['children'] as $child)  {
                $result += evaluate($child);
            }
            break;
        case 'multiply':
            $result = 1;
            foreach ($exp['children'] as $child)  {
                $result *= evaluate($child);
            }
            break;
        case 'fraction':
            $result = evaluate($exp['top']) / evaluate($exp['bottom']);
            break;
    }
    return $result;
}

giving

Expression 1 evaluates to 600
Expression 2 evaluates to 200
Expression 3 evaluates to 1.1

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.