Search code examples
phpforeach

php foreach (class->function as $val) doesn't return array


I've a class's function I use on a foreach loop. I can return a value (even if it's an array) but not an associative array

foreach ($this->myfunction($param1,$param2) as $val){
var_dump($val);
}

private function myFunction($param1,$param2){
  $returnArray = [];
  $settingArray = [];
  ...
  return $returnArray; //works but I need $settingArray
  return ['returnArray'=>$returnArray,'settingArray'=>$settingArray]; //fails: returns only $returnArray array (not associative array $val['returnArray'])
  return array($returnArray,$settingArray]; //fails: returns only $returnArray array
}

I can assign values in class for this, but I want to avoid this and also I'm trying to understand why there is this error. Thank you.

I would like to get the 2 arrays in foreach $val


Solution

  • There is problem with the private function which you have used. Whenever you are trying to return an associative array, return the array specifying key and their values. These keys can then be used to catch the values. Check my demo below:

    <?php
    
      class MyClass{
        public $param1;
        public $param2;
        public function concatVal($param1, $param2){
            foreach ($this->myfunction($param1,$param2) as $val){
                var_dump($val);
            }
        }
    
        private function myFunction($param1, $param2){
          $status = "";
          $message = "";
          $returnArray = [];
          $settingArray = [];
          $newWord = "some new word";
          $newWordInMiddle = $param1." ".$newWord." ".$param2;
          $newWordInEnd = $param1." ".$param2." ".$newWord;
          $status = "success";
          $message = "done";
    
          //return Array
          $returnArray = [
            'status' => $status,
            'message' => $message
          ];
    
          //settings Array
          $settingArray = [
            'newWordInMiddle' => $newWordInMiddle,
            'newWordInEnd' => $newWordInEnd
          ];
    
          //returning associative array here
          return array(
            'returnArray' => $returnArray,
            'settingArray' => $settingArray,
          );
    
        }
      }
    
      $myObj = new MyClass;
      $myObj->concatVal("Hello", "There");
    ?>