Returning all the values in the function, PHP

bookeraward1

I am new to php and am having trouble figuring out how to make sure that my function returns all the values,in the function below I want to make sure that when I call my function it returns all my three $parameters,for some reason it only is returning my $parameter1.

  public static function data($parameter){
    foreach($newlist as $value){
       if($value[0]=='age'){
          $parameter1 =new Age($value[1],$value[2]);
          return $parameter1;
        }
       if($value[0]== 'name'){
         $parameter2 =new Name($value[1],$value[2]); 
         return $parameter2;
        }
        if($value[0]== 'id'){
         $parameter3 =new Id($value[1],$value[2],$value[3]); 
         return $parameter3;
        }
        return array($parameter1,$parameter2,parameter3); //Here i want to make sure that when i call my function data, it returns an array of all my three parameters.
    }
  }
Jim

return will immediately end the function and return the value. This means when return $parameter1; is reached the function ends and returns.

You can get rid of the single return statements and move the array return outside of the loop (note that you'll likely want to check that the parameters have actually been found):

public static function data($parameter){
    foreach($newlist as $value){
       if($value[0]=='age'){
          $parameter1 =new Age($value[1],$value[2]);
        }
       if($value[0]== 'name'){
         $parameter2 =new Name($value[1],$value[2]); 
        }
        if($value[0]== 'id'){
         $parameter3 =new Id($value[1],$value[2],$value[3]); 
        }
    }
    return array($parameter1,$parameter2,parameter3);
  }

This is a fundamental part of PHP, I would recommend spending some time playing around with variations of the above so that you can get an idea of how the return keyword works.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related