PHP의 배열
다음 문서인 PHP의 배열에서는 PHP에서 배열을 만드는 방법에 대한 개요를 제공합니다. 배열은 유사한 데이터 유형의 모음입니다. 배열은 단일 변수에 여러 값을 저장합니다. 값을 변수로 저장할 수도 있는데 배열이 필요한 이유는 무엇입니까? 숫자 5처럼 제한된 데이터의 값을 저장하는 것은 가능하지만, 숫자가 100이나 200으로 증가하면 100개의 값을 100개의 변수에 저장해야 하는데 이는 약간 어렵습니다. 따라서 이를 배열에 저장합니다. 이것이 배열을 사용하는 이유입니다.
광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사무료 소프트웨어 개발 과정 시작
웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등
PHP에서 배열을 만드는 방법은 무엇인가요?
구문:
variablename = array();
또는
variablename[i] = value;
변수 이름이 변수 이름인 경우 i는 키이거나 인덱스 값은 요소 값입니다.
배열 생성 예시
$colors = array("Red","Green","Blue");
배열의 길이를 계산하려면 count 키워드를 사용합니다.
$length = count($colors); // output is 3
배열의 각 값을 배열의 요소라고 합니다. 배열 인덱스는 0부터 시작합니다. 배열의 마지막 요소 인덱스는 배열 전체 길이에서 1을 뺀 값입니다.
위의 예시에서 Red의 인덱스는 0, Green은 1, Blue는 2입니다. 따라서 인덱스나 키를 사용하여 배열에 액세스하는 것이 더 쉬워집니다. 배열의 각 인덱스에서 값을 얻으려면 주어진 배열을 반복합니다. 배열을 반복하려면 foreach 루프나 for 루프를 사용합니다.
PHP에서 어레이는 어떻게 작동하나요?
for Each 및 for와 같은 루프는 배열을 반복하는 데 사용됩니다. 각 배열에는 0부터 시작하는 인덱스가 있습니다.
PHP의 배열 유형
PHP에는 세 가지 유형의 배열이 있습니다. 각 배열 유형을 자세히 알아보겠습니다.
- 숫자형 또는 인덱스 배열
- 연관배열
- 다차원 배열
1. 숫자형 배열
인덱스가 항상 숫자인 이 배열 유형에서는 문자열이 될 수 없습니다. 대신, 원하는 수의 요소와 모든 유형의 요소를 저장할 수 있습니다.
구문:
variable name = array("value1","value2","value3","value4")
코드:
<?php //Example to demonstrate numeric array $input = array("Apple", "Orange", "Banana", "Kiwi"); //Here, to get these values we will write like echo $input[0] . "\n"; // will give Apple echo $input[1] . "\n"; // will give Orange echo $input[2] . "\n"; // will give Banana echo $input[3] . "\n"; // will give Kiwi // To get the length of array we will use count echo "The count of the array is " . count($input); // will give 4 echo "\n"; //To print the array we can use print_r($input); ?>
출력:
또는
숫자 배열을 선언하는 다른 방법은 다음 프로그램입니다. 이 프로그램에서는 값을 수정하고 인쇄하는 방법도 살펴보겠습니다.
코드:
<?php //Example to demonstrate numeric array in another way $input[0] = "Apple"; $input[1] = "Orange"; $input[2] = "Banana"; $input[3] = "Kiwi"; // To get Kiwi we will write like echo $input[3]."<br>"; // will give Kiwi //To modify Orange value $input[1] = "Mango"; // Now echo $input[1] will give Mango echo $input[1]."<br>"; // Mango //To print the array we can use print_r($input); ?>
출력:
이제 for 루프를 사용하여 배열을 탐색하는 방법을 배웁니다
코드:
<?php //Example to demonstrate for loop on a numeric array //declaring the array $input = array("Apple", "Orange", "Banana", "Kiwi", "Mango"); //the for loop to traverse through the input array for($i=0;$i<count($input); $i++) { echo $input[$i]; echo "<br>"; } ?>
출력:
2. 연관배열
이 배열은 키-값 쌍 형식으로, 키는 배열의 인덱스이고 값은 배열의 요소입니다.
구문:
$input = array("key1"=>"value1", "key2"=>"value2", "key3"=>"value3", "key4"=>"value4");
또는
배열 키워드 없이 연관 배열을 선언하는 다른 방법
$input[$key1] = $value1; $input[$key2] = $value2; $input[$key3] = $value3; $input[$key4] = $value4;
코드:
<?php //Example to demonstrate associative array //declaring an array $input = array( "Jan"=>31, "Feb"=>28, "Mar"=>31, "Apr"=>30); // the for loop to traverse through the input array foreach($input as $in) { echo $in."<br>";} ?>
출력:
3. 다차원 배열
이 배열은 배열의 값이 배열을 담고 있는 배열의 배열입니다.
구문:
$input =array( array('value1', 'value2', 'value3'), array('value4', 'value5', 'value6'), array('value7', 'value8', 'value9'));,
코드:
<?php //Example to demonstrate multidimensional array // declaring a multidimensional array $input = array ("colors"=>array ("Red", "Green", "Blue"), "fruits"=>array ("Apple", "Orange", "Grapes"), "cars"=>array ("Skoda", "BMW", "Mercedes") ); //the foreach loop to traverse through the input array foreach($input as $key=>$value) { echo $key .'--'. "<br>"; foreach($value as $k=>$v) {echo $v ." ";} echo "<br>"; } ?>
출력:
또는
연관배열의 다차원 배열
코드:
<?php //Example to demonstrate multidimensional array // declaring a multidimensional array $input = array( "The_Alchemist" => array ( "author" => "Paulo Coelho", "type" => "Fiction", "published_year" => 1988), "Managing_Oneself" => array( "author" => "Peter Drucker", "type" => "Non-fiction", "published_year" => 1999 ),"Measuring_the_World" => array( "author" => "Daniel Kehlmann", "type" => "Fiction", "published_year" => 2005 )); //the foreach loop to traverse through the input array //foreach to loop the outer array foreach($input as $book) { echo "<br>"; // foreach to loop the inner array foreach($book as $key=>$value) { echo $key." ". $value. "<br>";} }?>
출력:
PHP의 배열 방법
다음은 PHP의 Array 메소드입니다.
1. Count() 메소드
이 방법은 배열의 요소 수를 계산하는 데 사용됩니다.
구문:
Count(array, mode)
카운트가 필수인 경우 모드는 선택사항입니다.
코드:
<?php //Example to demonstrate use of in_array method //declaring associative array $input=array('English','Hindi','Marathi'); //counting the number of elements in the given array echo count($input); ?>
출력:
2. Array_walk() 메소드
이 방법은 두 개의 매개변수를 입력으로 사용합니다. 첫 번째 매개변수는 입력 배열이고, 두 번째 매개변수는 선언된 함수의 이름입니다. 이 방법은 배열의 각 요소를 반복하는 데 사용됩니다.
구문:
array_walk(array, function_name, parameter...)
배열이 필요한 경우 function_name이 필요합니다
매개변수는 선택사항입니다
코드:
<?php //Example to demonstrate use of array_walk method //creating a function to print the key and values of the given array function fun($val, $k) { echo $k. " --" .$val ."\n"; } // declaring associative array $input=array("e"=>'English', "h"=>'Hindi', "m"=>'Marathi'); //passing this array as a first parameter to the function // array_walk, //second paramter as the name of the function being called array_walk($input,"fun"); ?>
Output:
3. In_array() method
This method performs a search on the array, whether the given array contains a particular value or not. If found or not found, it will execute respective if, else block
Syntax:
in_array(search_value, array_name)
Where both the parameters are required
Code:
<?php //Example to demonstrate use of in_array method // declaring associative array $input=array('English','Hindi','Marathi', "Maths", "Social Science"); // using in_array to find Maths in given array if(in_array("Maths", $input)) { echo "Found Maths in the given array"; } else { echo "Did not find Maths in the given array"; } ?>
Output:
4. Array_pop() method
This method removes the last element from the given array.
Syntax
array_pop(array_name)
Code:
<?php //Example to demonstrate use of array_pop method // declaring array $input=array('English','Hindi','Marathi'); // before using array_pop on the given array print_r($input); // after using array_pop method on the given array array_pop($input); echo "\n "; print_r($input); ?>
Output:
5. Array_push() method
This method adds given elements at the end of the array.
Syntax:
array_push(array_name, value1, value2, ...)
Code:
<?php //Example to demonstrate use of array_push method // declaring array $input=array('English','Hindi','Marathi'); // before using array_push on the given array print_r($input); // after using array_push method on the given array array_push($input, "Economics", "Maths", "Social Science"); echo "\n"; //printing the array print_r($input); ?>
Output:
6. Array_shift() method
This method removes and returns the first element of the array.
Syntax:
array_shift(array_name)
Code:
<?php //Example to demonstrate use of array_push method // declaring array $input=array('English','Hindi','Marathi'); // before using array_shift on the given array print_r($input); echo "\n"; // after using array_shift method on the given array echo array_shift($input); ?>
Output:
7. Array_unshift() method
This method inserts given elements into the beginning of the array.
Syntax:
array_unshift(array_name, value1, value2,…)
Code:
<?php //Example to demonstrate use of array_push method // declaring array $input=array('English','Hindi','Marathi'); // before using array_unshift on the given arrayprint_r($input); echo "\n"; // after using array_unshift method on the given array array_unshift($input, "Economics"); print_r($input); ?>
Output:
8. Array_reverse() method
This method is used to reverse the elements of the array.
Syntax:
array_reverse(array_name, preserve)
where array_name is required,
preserve is optional
Code:
<?php //Example to demonstrate use of in_array method // declaring associative array $input=array("e"=>'English',"h"=>'Hindi',"m"=>'Marathi'); // array before reversing the elements print_r($input); echo "\n"; // printing the reverse // array after reversing the elements print_r(array_reverse($input)); ?>
Output:
Conclusion
This article covers all levels of concepts, simple and complex, of the topic arrays in PHP. I hope you found this article interesting and informative for the learning purpose.
위 내용은 PHP의 배열의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

PHP의 마법 방법은 무엇입니까? PHP의 마법 방법은 다음과 같습니다. 1. \ _ \ _ Construct, 객체를 초기화하는 데 사용됩니다. 2. \ _ \ _ 파괴, 자원을 정리하는 데 사용됩니다. 3. \ _ \ _ 호출, 존재하지 않는 메소드 호출을 처리하십시오. 4. \ _ \ _ get, 동적 속성 액세스를 구현하십시오. 5. \ _ \ _ Set, 동적 속성 설정을 구현하십시오. 이러한 방법은 특정 상황에서 자동으로 호출되어 코드 유연성과 효율성을 향상시킵니다.

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.
