伙计们我正在尝试在函数中使用数组,但出现此错误[关闭]

问题描述 投票:-4回答:4

这是我的代码

$ x = array('1','2','3');

function myTest() {
  global $x;
  foreach($x as $y){
  echo $y.'<br>';
  }
} 

myTest();  // run function

这是错误

enter image description here

php laravel
4个回答
0
投票

在刀片中尝试一下:

@php
 $x = array('1', '2', '3');
@endphp

@foreach($x as $y)
 {{ $y }} <br>
@endforeach

0
投票

您应该使用$ x的全局密钥:

global $x;

$x = array('1', '2', '3');

function myTest() {
  global $x;
  foreach($x as $y){
      echo $y.'<br>';
      }
    } 

myTest();  // run function

或者您可以使用$ GLOBALS ['x'];

global $x;

$x = array('1', '2', '3');

function myTest() {
  foreach($GLOBALS['x'] as $y){
      echo $y.'<br>';
      }
    } 

myTest();  // run function

或者您可以使用$ x作为参数

$x = array('1', '2', '3');

function myTest($val) {
  foreach($val as $y){
      echo $y.'<br>';
      }
    } 

myTest($x);  // run function

0
投票

您不能先初始化数组,然后再将其声明为全局数组,因为发生的事情是在将函数$x视为数组之前,但是在函数内部声明为全局数组之后,它无法继承如前所述的属性。这样做是完全错误的方法。相反,您必须在函数中声明并初始化为[]

function myTest() {
  global $x = array('1', '2', '3');
  foreach($x as $y){
  echo $y.'<br>';
  }
} 
myTest();  // run function

从现在开始,它将对所有功能都是全局的。


-3
投票

请在控制器中编写代码,然后将其传递到视图中并遍历该值会更好,但您可以编写此代码

© www.soinside.com 2019 - 2024. All rights reserved.