your programing

[]로 값을 추가하기 전에 PHP 배열을 선언해야합니까?

lovepro 2020. 10. 14. 08:15
반응형

[]로 값을 추가하기 전에 PHP 배열을 선언해야합니까?


$arr = array(); // is this line needed?
$arr[] = 5;

첫 번째 줄없이 작동한다는 것을 알고 있지만 실제로는 종종 포함됩니다.

그 이유는 무엇입니까? 그것 없이는 안전하지 않습니까?

나는 또한 이것을 할 수 있다는 것을 안다.

 $arr = array(5);

하지만 항목을 하나씩 추가해야하는 경우에 대해 이야기하고 있습니다.


새 배열을 선언하지 않고 배열을 생성 / 업데이트하는 데이터가 어떤 이유로 든 실패하면 배열을 사용하려는 향후 코드 E_FATAL는 배열이 존재하지 않기 때문입니다.

예를 들어 foreach()는 배열이 선언되지 않았고 여기에 값이 추가되지 않은 경우 오류를 발생시킵니다. 그러나 선언 한 경우와 같이 배열이 단순히 비어 있으면 오류가 발생하지 않습니다.


PHP 문서가arrays 실제로 문서에서 이에 대해 이야기 하고 있음을 지적하고 싶었습니다 .

PHP 사이트에서 제공되는 코드 스 니펫 :

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

" $arr아직 존재하지 않으면 생성 될 것이므로 이것은 어레이를 생성하는 또 다른 방법이기도합니다."

그러나 다른 답변에서 언급했듯이 ...하지 않으면 모든 종류의 나쁜 일이 발생할 수 있으므로 변수에 대한 값을 선언해야합니다.


Php는 느슨하게 입력 된 언어입니다. 완벽하게 받아 들여집니다. 즉, 실제 프로그래머는 항상 vars를 선언합니다.


당신을 쫓는 코더들을 생각해보세요! 그냥 볼 경우 $arr[] = 5, 당신은 무엇 아무 생각이없는 $arr범위에서 모든 앞의 코드를 읽지 않고 될 수 있습니다. 명시적인 $arr = array()줄은 그것을 명확하게합니다.


그것은 단지 좋은 습관입니다. 루프 내부에 배열에 추가했지만 (상당히 일반적인 관행), 해당 루프 외부의 배열에 액세스한다고 가정 해 보겠습니다. 배열 선언이 없으면 루프에 넣지 않으면 코드에서 오류가 발생합니다.


값을 추가하기 전에 배열을 선언하는 것이 좋습니다. 위에서 언급 한 모든 것 외에도 배열이 루프 내부에 있으면 의도하지 않게 요소를 배열로 푸시 할 수 있습니다. 나는 이것이 값 비싼 버그를 만드는 것을 방금 관찰했습니다.

//Example code    
foreach ($mailboxes as $mailbox){
       //loop creating email list to get
       foreach ($emails as $email){
          $arr[] = $email;
       }
       //loop to get emails
       foreach ($arr as $email){
       //oops now we're getting other peoples emails
       //in other mailboxes because we didn't initialize the array
       }
}

배열을 사용하기 전에 선언하지 않으면 실제로 문제가 발생할 수 있습니다. 방금 찾은 경험 중 하나는이 테스트 스크립트를 다음과 같이 호출했습니다. indextest.php? file = 1STLSPGTGUS 예상대로 작동합니다.

//indextest.php?file=1STLSPGTGUS
$path['templates']     = './mytemplates/';
$file['template']      = 'myindex.tpl.php';
$file['otherthing']      = 'otherthing';
$file['iamempty']    = '';

print ("path['templates'] = " . $path['templates'] . "<br>");
print ("file['template'] = " . $file['template'] . "<br>");
print ("file['otherthing'] = " . $file['otherthing'] . "<br>");
print ("file['iamempty'] = " . $file['iamempty'] . "<br>");

print ("file['file'] = " . $file['file'] . "<br>");// should give: "Notice: Undefined index: file"
print ("file = " . $file);// should give: "Notice: Undefined index: file"

//the Output is:
/*
path['templates'] = ./mytemplates/
file['template'] = myindex.tpl.php
file['otherthing'] = otherthing
file['iamempty'] =

Notice: Undefined index: file in D:\Server\Apache24\htdocs\DeliverText\indextest.php on line 14
file['file'] =

Notice: Array to string conversion in D:\Server\Apache24\htdocs\DeliverText\indextest.php on line 15
file = Array
*/

이제 내가 구입 한 다른 스크립트의 파일이 맨 위에 있어야합니다. 배열 $ file의 값이 완전히 잘못된 반면 array $ path는 괜찮습니다. "checkgroup.php"가 유죄입니다.

//indextest.php?file=1STLSPGTGUS
require_once($_SERVER['DOCUMENT_ROOT']."/IniConfig.php");
$access = "PUBLIC";
require_once(CONFPATH . "include_secure/checkgroup.php");
$path['templates']     = './mytemplates/';
$file['template']      = 'myindex.tpl.php';
$file['otherthing']      = 'otherthing.php';
$file['iamempty']    = '';

print ("path['templates'] = " . $path['templates'] . "<br>");
print ("file['template'] = " . $file['template'] . "<br>");
print ("file['otherthing'] = " . $file['otherthing'] . "<br>");
print ("file['iamempty'] = " . $file['iamempty'] . "<br>");

print ("file['file'] = " . $file['file'] . "<br>");
print ("file = " . $file);

//the Output is:
/*
path['templates'] = ./mytemplates/
file['template'] = o
file['otherthing'] = o
file['iamempty'] = o
file['file'] = o
file = oSTLSPGTGUS
*/

이전에 어레이를 초기화하면 문제 없습니다!

//indextest.php?file=1STLSPGTGUS
require_once($_SERVER['DOCUMENT_ROOT']."/IniConfig.php");
$access = "PUBLIC";
require_once(CONFPATH . "include_secure/checkgroup.php");

$path = array();
$file = array();

$path['templates']     = './mytemplates/';
$file['template']      = 'myindex.tpl.php';
$file['otherthing']      = 'otherthing.php';
$file['iamempty']    = '';

print ("path['templates'] = " . $path['templates'] . "<br>");
print ("file['template'] = " . $file['template'] . "<br>");
print ("file['otherthing'] = " . $file['otherthing'] . "<br>");
print ("file['iamempty'] = " . $file['iamempty'] . "<br>");

print ("file['file'] = " . $file['file'] . "<br>");
print ("file = " . $file);

//the Output is:
/*
path['templates'] = ./mytemplates/
file['template'] = myindex.tpl.php
file['otherthing'] = otherthing.php
file['iamempty'] =
file['file'] =
file = Array
*/

그래서 나중에 어떤 문제가 생길지 모르고 시간을 절약하기 위해 결국 더 많은 것을 낭비하게 될 수도 있으므로 변수를 초기화하는 것이 얼마나 중요한지 깨달았습니다. 전문가가 아닌 저와 같은 분들에게 도움이되기를 바랍니다.


오류 검사에 따라 다릅니다. Strict에 대한 오류보고가있는 경우 알림을 제공하지만 기술적으로는 여전히 작동합니다.


전역 변수로 필요하거나 다른 함수에서 동일한 배열을 반복해서 재사용하려는 경우에 좋습니다.


이것은 당신의 코드입니다

$var[]  = 2;
print_r($var)

Works fine! until someone declares the same variable name before your charming code

$var = 3; 

$var[]  = 2;
print_r($var)

Warning: Cannot use a scalar value as an array

Oops!

This is one possible (sometimes unpredictable) case, so yes $var = array() is needed

$var = 3;
$var = array();
$var[]  = 2;
print_r($var)

Output

Array
(
    [0] => 2
)

Agree with @djdy, just one alternative I'd love to post:

<?php

// Passed array is empty, so we'll never have $items variable available.
foreach (array() AS $item)
    $items[] = $item;

isset($items) OR $items = array(); // Declare $items variable if it doesn't exist

?>

참고URL : https://stackoverflow.com/questions/8246047/is-it-necessary-to-declare-php-array-before-adding-values-with

반응형