Modifying Elements by Index
Coddy PHP 여정의 기초 섹션에 포함된 레슨 — 71개 중 37번째.
인덱스를 사용하여 배열 요소에 접근하는 방법을 배웠습니다. 이제 그 요소들을 변경하는 방법을 살펴보겠습니다. 배열 요소를 수정할 때는 동일한 대괄호 구문을 사용하지만, 할당과 함께 사용합니다.
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Blueberry";
echo $fruits[1]; // Blueberry
?>여기서 인덱스 1의 "Banana"를 "Blueberry"로 교체했습니다. 원래 값은 사라졌습니다—배열은 변경 이력을 유지하지 않습니다.
인덱스를 알면 어떤 요소든 수정할 수 있습니다:
<?php
$scores = [85, 90, 78];
$scores[0] = 95; // Update first score
$scores[2] = 82; // Update last score
echo $scores[0]; // 95
echo $scores[2]; // 82
?>리스트의 데이터를 업데이트해야 할 때 유용합니다—오타를 수정하거나, 가격을 업데이트하거나, 사용자 상태를 변경하는 것처럼요. 인덱스는 PHP에게 정확히 어떤 요소를 교체할지 알려주며, 다른 모든 요소는 그대로 둡니다.
챌린지
쉬움쉼표로 구분된 값들이 포함된 입력 한 줄을 읽어 색상 목록을 나타냅니다 (예: Red,Green,Blue,Yellow).
그 다음 세 개의 추가 입력을 읽으세요:
- 수정할 첫 번째 인덱스를 나타내는 정수
index1 - 해당 인덱스의 새 값을 나타내는 문자열
newValue1 - 수정할 두 번째 인덱스를 나타내는 정수
index2
쉼표로 구분된 입력으로부터 배열을 생성한 후:
index1위치의 요소를newValue1로 수정하세요index2위치의 요소를Purple로 수정하세요
수정된 배열 요소를 인덱스 0부터 마지막 인덱스까지 순서대로 별도의 줄에 출력하세요.
예제:
입력값이 Red,Green,Blue,Yellow, 0, Orange, 그리고 2인 경우 출력은 다음과 같아야 합니다:
Orange
Green
Purple
Yellow입력값이 Apple,Banana,Cherry,Mango,Kiwi, 1, Grape, 그리고 4인 경우 출력은 다음과 같아야 합니다:
Apple
Grape
Cherry
Mango
Purple치트 시트
배열 요소를 수정하려면 인덱스를 대괄호와 함께 사용하여 할당하세요:
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Blueberry"; // Changes "Banana" to "Blueberry"
echo $fruits[1]; // Blueberry
?>다른 인덱스를 지정하여 여러 요소를 수정할 수 있습니다:
<?php
$scores = [85, 90, 78];
$scores[0] = 95; // Update first element
$scores[2] = 82; // Update last element
?>원래 값은 대체되며 보존되지 않습니다. 배열의 다른 요소는 변경되지 않습니다.
직접 해보기
<?php
// 쉼표로 구분된 색상을 읽기
$colorsInput = trim(fgets(STDIN));
$colors = explode(',', $colorsInput);
// 수정 입력값 읽기
$index1 = intval(trim(fgets(STDIN)));
$newValue1 = trim(fgets(STDIN));
$index2 = intval(trim(fgets(STDIN)));
// TODO: 여기에 코드 작성
// 1. index1 위치의 요소를 newValue1로 수정
// 2. index2 위치의 요소를 "Purple"로 수정
// 각 요소를 별도의 줄에 출력
foreach ($colors as $color) {
echo $color . "\n";
}
?>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators6Arrays Part 1 - Indexed
Introduction to ArraysCreating Indexed ArraysAccessing Elements by IndexModifying Elements by IndexArray Size with CountAdding Elements to an ArrayRecap - Managing a Simple List