2014-04-10 4 views
0

배열에있는 모든 것을 하나씩 밀어 넣는 방법이 있는지 궁금합니다. 예를 들어 :배열 값을 1 씩 밀어 넣기

//This will add the first error to array 
$error[] = "You must provide a first_name"; 

//This will add the second error to array 
$error[] = "You must provide a last_name"; 

//This error i want to add at the first index of the array, while pushing the previous two that are already added down a value. But doing it the way i've been doing it just replaces the first index 
$error[0] = "This will push the other two errors down one index"; 

실제로 배열 인덱스의 첫 번째 값을 제거받지 않고이 작업을 수행하는 어쨌든이있다.

FIXED 버전 : Sharanya 두타에

//This will add the first error to array 
$error[] = "You must provide a first_name"; 

//This will add the second error to array 
$error[] = "You must provide a last_name"; 

//This error i want to add at the first index of the array, while pushing the previous two that are already added down a value. But doing it the way i've been doing it just replaces the first index 
array_unshift($error, "This will push the other two errors down one index"); 

감사합니다.

+0

다음 대답 중 하나를 [accepting] (http://stackoverflow.com/help/accepted-answer)으로 간주 할 수 있습니다. –

+0

예. 죄송합니다. 시간 제한이있는 문제가 있습니다. 완료했습니다 –

답변

3

가 내장 된 PHP 함수 array_unshift 당신의 목적을 제공합니다 :

$error = array(); 
$error[] = "You must provide a first_name"; 
$error[] = "You must provide a last_name"; 
array_unshift($error, "This will push the other two errors down one index"); 
print_r($error); 

출력은 다음과 같습니다

Array 
(
    [0] => This will push the other two errors down one index 
    [1] => You must provide a first_name 
    [2] => You must provide a last_name 
) 

DEMO

+0

아, 정말 고마워요. 이것은 내가 필요한 것입니다. –

+1

당신은 천만에요. –

-1

미친 더러운 해킹 큰 값에서 추가 시작합니다. : ^)

$error[1000] = "You must provide a first_name"; 
$error[] = "You must provide a last_name"; 
$error[0] = "This will push the other two errors down one index";