[]를 사용하여 값을 추가하기 전에 PHP 어레이를 선언해야 합니까?
$arr = array(); // is this line needed?
$arr[] = 5;
첫 번째 줄 없이도 작동한다는 건 알지만, 종종 연습에 포함되곤 해요.
이유가 뭐야?그게 없으면 안전하지 않나요?
이것도 할 수 있어요.
$arr = array(5);
아이템을 하나씩 추가해야 하는 경우를 말하는 거예요.
새로운 어레이를 선언하지 않고 어레이를 작성/갱신하는 데이터가 어떠한 이유로 실패하면 어레이를 사용하려고 하는 향후 코드는 모두 실패합니다.E_FATAL
어레이가 존재하지 않기 때문입니다.
예를들면,foreach()
어레이가 선언되지 않고 값이 추가되지 않은 경우 에러가 발생합니다.다만, 어레이가 비어 있는 경우는, 선언했을 때와 같이 에러는 발생하지 않습니다.
의 PHP 설명서에서 실제로 이에 대해 설명한다는 점을 지적하고자 합니다.
PHP 사이트에서 코드 스니펫을 첨부합니다.
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type
"만약에.
$arr
아직 존재하지 않습니다.그것은 작성됩니다.이것도 어레이를 작성하는 대체 방법입니다.」
하지만, 다른 답변들도 언급했듯이...변수 값을 선언해야 합니다. 그렇지 않으면 모든 종류의 나쁜 일이 발생할 수 있기 때문입니다.
Php는 느슨하게 입력된 언어입니다.충분히 받아들일 수 있다.말하자면, 진짜 프로그래머들은 항상 그들의 대표들을 선언한다.
널 쫓는 코드들을 생각해 봐!보기만 해도$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.file?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
*/
이제 구입한 다른 스크립트의 파일을 맨 위에 놓으면 어레이 $path가 정상일 때 어레이 $file 값이 완전히 잘못된 것을 알 수 있습니다. "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
*/
이렇게 해서 변수를 초기화하는 것이 얼마나 중요한지 알게 되었습니다.나중에 어떤 문제가 생길지 모르기 때문입니다.또, 단지 시간을 절약하고 싶다고 하는 것만으로, 마지막에 더 많은 것을 낭비하게 될 수도 있습니다.나처럼 프로답지 못한 사람들에게 도움이 되었으면 좋겠어.
오래된 질문이지만 어레이가 선언되지 않으면 코드가 심플해지는 하나의 사용 사례이기 때문에 공유합니다.
속성 중 하나를 인덱싱해야 하는 개체 목록이 있다고 가정합니다.
// $list is array of objects, all having $key property.
$index = [];
foreach ($list as $item)
$index[$item->key][] = $item; // Dont care if $index[$item->key] already exists or not.
에러 체크에 의해서 다릅니다.strict에 대한 오류 보고가 있는 경우 알림이 표시되지만 기술적으로는 오류 보고가 없어도 됩니다.
글로벌 변수로 필요하거나 동일한 어레이를 여러 기능으로 반복해서 재사용하려는 경우에 적합합니다.
이것은 당신의 코드입니다.
$var[] = 2;
print_r($var)
동작은 양호합니다!누군가가 당신의 매력적인 코드 앞에 같은 변수 이름을 선언할 때까지
$var = 3;
$var[] = 2;
print_r($var)
경고: 스칼라 값을 배열로 사용할 수 없습니다.
아뿔싸!
때로는 할 수 없는) 케이스이기 「네」는 「네」, 「네, 「예」는 「예」입니다.$var = array()
$var = 3;
$var = array();
$var[] = 2;
print_r($var)
산출량
Array
(
[0] => 2
)
★★★의 foreach
데이터가 불분명한 경우에는 다음과 같이 할 수 있습니다.
foreach($users ?? [] as $user) {
// Do things with $user
}
if$users
되지 않았습니다( does 정정 (ales( alesalesmodulemodule alesmodulemoduleales alesalesalesales alesalesales alesalesalesales ) 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
?>
언급URL : https://stackoverflow.com/questions/8246047/is-it-necessary-to-declare-php-array-before-adding-values-with
'itsource' 카테고리의 다른 글
문자열 표현을 사용하지 않고 설정된 표준 시간대로 날짜 만들기 (0) | 2023.02.06 |
---|---|
array_module 및 키 번호 변경 (0) | 2023.02.06 |
오류 - npm - node.js를 사용하여 mariasql 패키지를 설치하는 중 (0) | 2023.02.06 |
@Mock 주석 뒤에 있는 모의 인스턴스가 null입니다. (0) | 2023.02.06 |
Java의 String 상수 풀은 힙과 스택 중 어디에 있습니까? (0) | 2023.02.06 |