$arr = array(); // is this line needed?
$arr[] = 5;
첫 번째 줄없이 작동한다는 것을 알고 있지만 실제로는 종종 포함됩니다.
그 이유는 무엇입니까? 그것 없이는 안전하지 않습니까?
나는 또한 이것을 할 수 있다는 것을 안다.
$arr = array(5);
하지만 항목을 하나씩 추가해야하는 경우에 대해 이야기하고 있습니다.
$arr = array(); // is this line needed?
$arr[] = 5;
첫 번째 줄없이 작동한다는 것을 알고 있지만 실제로는 종종 포함됩니다.
그 이유는 무엇입니까? 그것 없이는 안전하지 않습니까?
나는 또한 이것을 할 수 있다는 것을 안다.
$arr = array(5);
하지만 항목을 하나씩 추가해야하는 경우에 대해 이야기하고 있습니다.
답변:
새 배열을 선언하지 않고 배열을 생성 / 업데이트하는 데이터가 어떤 이유로 든 실패하면 배열을 사용하려는 향후 코드 E_FATAL는 배열이 존재하지 않기 때문입니다.
예를 들어 foreach()는 배열이 선언되지 않았고 여기에 값이 추가되지 않은 경우 오류를 발생시킵니다. 그러나 선언 한 경우처럼 배열이 단순히 비어 있으면 오류가 발생하지 않습니다.
foreach예와 오류가 트리거된다는 사실이 실행중인 PHP 버전에 따라 분명히 다르기 때문에 찬성되었습니다 .
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는 느슨하게 입력 된 언어입니다. 완벽하게 받아 들여집니다. 즉, 실제 프로그래머는 항상 var를 선언합니다.
당신을 쫓는 코더들을 생각해보세요! 그냥 볼 경우 $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
*/
그래서 나중에 어떤 문제가 생길지 모르고 시간을 절약하기 위해 결국 더 많은 것을 낭비하게 될 수도 있으므로 변수를 초기화하는 것이 얼마나 중요한지 깨달았습니다. 전문가가 아닌 저와 같은 사람들에게 도움이 되길 바랍니다.
foreach데이터가 확실하지 않은 경우 For 루프는 다음과 같이 할 수 있습니다.
foreach($users ?? [] as $user) {
// Do things with $user
}
$users이 설정되지 않은 경우 (null coalesce does isset($users)) 빈 배열이 표시 []되므로 PHP는 foreach오류, 경고 또는 알림없이 루프 할 항목이 없으므로 루프 를 반복하지 않습니다.
나는 코멘트 / 답변의 일부에 동의하지 않습니다. 일종의 안전망과 같이 단순히 빈 배열을 선언하거나 변수를 초기화해야한다고 생각하지 않습니다. 이러한 접근 방식은 제 생각에는 나쁜 프로그래밍입니다. 필요할 때 명시 적으로 수행하십시오.
당신이 하늘의 배열을 초기화해야하는 경우 그리고, 솔직히 생각 코드가 잘 구성 할 수 있다면, 나중에 또는 어떤 데이터를 확인하는 방법.
다음 코드는 무의미합니다. "의도"를 나타내지 않고 왜 초기화되었는지에 대해 사람들을 혼동시킬 수 있습니다 (기껏해야 읽고 처리하는 것이 무의미합니다).
$user = [];
$user['name'] = ['bob'];
두 번째 줄도 새 배열을 선언하며 실패하지 않습니다.
게시하고 싶은 대안 중 하나 인 @djdy에 동의합니다.
<?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
?>
array()빈 배열이면 foreach아무것도하지 않습니까?
$foo = array()배열로 변환 된 문자열이 아니라는 것이 분명합니다 ).