2

I want to create function display() to be called to display a sorted list of all previous names and marks entered. Name parameter should be set as optional. I am unable to call the function in the proper place. Note that the code is working without the function. I want to it to work by the function display(); Please help. Thanks

Here's my code:

<?php

session_start();

if(isset($_POST['lname']) && isset($_POST['marks'])){
    if ($_POST['marks']<=100){
        $_SESSION['info'][] = array($_POST['lname'] => $_POST['marks']);
    }elseif (isset($_SESSION['info'])) {
        $marks = array();
        foreach($_SESSION['info'] as $key =>$values){
            foreach($values as $name=>$mark){
                $marks[$key] = $mark;
            }
        }
        display();

        function display(){ 
            arsort($marks);
            foreach($marks as $key => $value){
                foreach($_SESSION['info'][$key] as $name => $marks){
                    printf("Name: %s &nbsp; Marks: %d &nbsp Grade: %s <br>", $name, $marks, CalcGrade($marks) );
                }
            }
        } 
    }
}

3 Answers 3

3

Try like this

  session_start();

 if(isset($_POST['lname']) && isset($_POST['marks'])){        
if ($_POST['marks']<=100){
  $_SESSION['info'][] = array($_POST['lname'] => $_POST['marks']);

 }elseif (isset($_SESSION['info'])) {
  $marks = array();
  foreach($_SESSION['info'] as $key =>$values){
       foreach($values as $name=>$mark){
            $marks[$key] = $mark;
   }
 }
 display($marks);

function display($marks){ 
arsort($marks);
 foreach($marks as $key => $value){
 foreach($_SESSION['info'][$key] as $name => $marks){
 printf("Name: %s &nbsp; Marks: %d &nbsp Grade: %s <br>", $name, $marks, CalcGrade($marks) );
      }
    }
  } 
}
  }
Sign up to request clarification or add additional context in comments.

Comments

2

As each function works for itself, you must either pass the variables you work with, or get it from the global namespace.

function display() {

    global $marks; 

    arsort($marks);

    ......
}

Or

function display($marks) {

    arsort($marks);

    ......
}

2 Comments

Its not working bro.. Fatal error: Call to undefined function display() in line 16 Here's my full code pastebin.com/ZsmfL0S3
First of all, you shoud pass the variable $marks to the function on line 16 of your code... but is it just me, or the closing brackets are much more than the opening ?
0

Define $marks in the function..in PHP functions can't get the value outside it by your above written codes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.