Array Size with Count
Coddy PHP 여정의 기초 섹션에 포함된 레슨 — 71개 중 38번째.
배열을 다룰 때, 배열에 얼마나 많은 요소가 포함되어 있는지 알아야 할 때가 많습니다. PHP는 바로 이 목적을 위해 count() 함수를 제공합니다.
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo count($fruits); // 3
?>이 함수는 배열의 총 요소 수를 반환합니다. 이것은 마지막 요소에 접근해야 할 때 특히 유용합니다. 인덱싱은 0부터 시작하므로, 마지막 인덱스는 항상 count($array) - 1입니다.
<?php
$colors = ["Red", "Green", "Blue", "Yellow"];
$lastIndex = count($colors) - 1;
echo $colors[$lastIndex]; // 노란색
?>이 접근 방식은 배열에 얼마나 많은 항목이 있는지에 관계없이 작동합니다. 요소가 3개이든 300개이든 상관없이, count()는 정확한 크기를 제공하여 코드를 유연하고 신뢰할 수 있게 만들어 줍니다.
챌린지
쉬움항목 목록을 나타내는 쉼표로 구분된 값들이 포함된 입력 한 줄을 읽습니다 (예: Laptop,Mouse,Keyboard,Monitor,Webcam).
이 입력으로 배열을 생성한 후, 다음을 수행하세요:
- 배열의 총 항목 수를 출력합니다
- 배열의 마지막 요소를 출력합니다 (
count()를 사용하여 마지막 인덱스를 계산하세요) - 배열의 뒤에서 두 번째 요소를 출력합니다
각 결과를 별도의 줄에 출력합니다.
예시:
입력이 Laptop,Mouse,Keyboard,Monitor,Webcam인 경우, 출력은 다음과 같아야 합니다:
5
Webcam
Monitor입력이 Apple,Banana,Cherry인 경우, 출력은 다음과 같아야 합니다:
3
Cherry
Banana직접 해보기
<?php
// 쉼표로 구분된 입력을 읽습니다
$input = trim(fgets(STDIN));
// 입력 문자열을 배열로 변환합니다
$items = explode(',', $input);
// TODO: 아래에 코드를 작성하세요
// 1. count()를 사용하여 전체 아이템 개수를 출력하세요
// 2. 마지막 요소를 출력하세요 (count()를 사용하여 마지막 인덱스를 계산하세요)
// 3. 뒤에서 두 번째 요소를 출력하세요
?>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
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