'array_unshift'로 추가하기
Coddy PHP 여정의 논리 & 흐름 섹션에 포함된 레슨. 68개 중 12번째.
array_push()는 배열의 끝에 요소를 추가하는 반면, array_unshift() 함수는 그 반대 작업을 수행합니다. 이 함수는 배열의 시작 부분에 하나 이상의 요소를 추가합니다. 이 함수는 원래 배열을 직접 수정하고 배열의 새로운 길이를 반환합니다.
기본 구문은 다음과 같습니다:
<?php
$tasks = ["buy groceries", "do laundry"];
array_unshift($tasks, "urgent meeting");
print_r($tasks); // Outputs: Array ( [0] => urgent meeting [1] => buy groceries [2] => do laundry )
?>새 요소가 인덱스 0이 되고 기존의 모든 요소가 더 높은 인덱스로 이동하는 것을 확인하세요. 이 인덱스 재지정은 자동으로 수행됩니다. array_unshift()가 적절한 순서를 유지하도록 모든 숫자 키를 업데이트합니다.
여러 요소를 한 번에 추가할 수도 있습니다:
<?php
$priorities = ["medium task"];
array_unshift($priorities, "high priority", "critical task");
print_r($priorities); // 출력: Array ( [0] => high priority [1] => critical task [2] => medium task )
?>이 함수는 list의 items에 우선순위를 지정해야 할 때 특히 유용합니다. 예를 들어 할 일 목록의 맨 위에 urgent tasks를 추가하거나 queue의 앞쪽에 high-priority items를 삽입할 때 사용할 수 있습니다.
챌린지
쉬움두 개의 입력을 받습니다. JSON 형식의 초기 notifications array와 추가할 새로운 urgent notification입니다. 두 입력을 읽고, JSON 문자열을 array로 변환한 다음, array_unshift()를 사용하여 urgent notification을 array의 beginning에 추가하고, print_r()를 사용하여 final array를 출력하세요.
입력 형식: 두 줄입니다. 첫 번째 줄에는 JSON array가 포함됩니다(예: ["meeting reminder","email received"]). 두 번째 줄에는 추가할 urgent notification이 포함됩니다.
예상 출력: urgent notification을 beginning에 추가한 후의 array를 print_r()를 사용하여 표시합니다.
직접 해보기
<?php
// Read the JSON array of notifications
$jsonInput = fgets(STDIN);
$notifications = (array)json_decode($jsonInput, true);
// Read the urgent notification to add
$urgentNotification = trim(fgets(STDIN));
// TODO: Write your code below to add the urgent notification to the beginning of the array
// 최종 배열을 출력합니다
print_r($notifications);
?>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 & 흐름의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러