다음 문서인 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PHP는 현대적인 프로그래밍, 특히 웹 개발 분야에서 강력하고 널리 사용되는 도구로 남아 있습니다. 1) PHP는 사용하기 쉽고 데이터베이스와 완벽하게 통합되며 많은 개발자에게 가장 먼저 선택됩니다. 2) 동적 컨텐츠 생성 및 객체 지향 프로그래밍을 지원하여 웹 사이트를 신속하게 작성하고 유지 관리하는 데 적합합니다. 3) 데이터베이스 쿼리를 캐싱하고 최적화함으로써 PHP의 성능을 향상시킬 수 있으며, 광범위한 커뮤니티와 풍부한 생태계는 오늘날의 기술 스택에 여전히 중요합니다.

PHP에서는 약한 참조가 약한 회의 클래스를 통해 구현되며 쓰레기 수집가가 물체를 되 찾는 것을 방해하지 않습니다. 약한 참조는 캐싱 시스템 및 이벤트 리스너와 같은 시나리오에 적합합니다. 물체의 생존을 보장 할 수 없으며 쓰레기 수집이 지연 될 수 있음에 주목해야합니다.

\ _ \ _ 호출 메소드를 사용하면 객체를 함수처럼 호출 할 수 있습니다. 1. 객체를 호출 할 수 있도록 메소드를 호출하는 \ _ \ _ 정의하십시오. 2. $ obj (...) 구문을 사용할 때 PHP는 \ _ \ _ invoke 메소드를 실행합니다. 3. 로깅 및 계산기, 코드 유연성 및 가독성 향상과 같은 시나리오에 적합합니다.

섬유는 PHP8.1에 도입되어 동시 처리 기능을 향상시켰다. 1) 섬유는 코 루틴과 유사한 가벼운 동시성 모델입니다. 2) 개발자는 작업의 실행 흐름을 수동으로 제어 할 수 있으며 I/O 집약적 작업을 처리하는 데 적합합니다. 3) 섬유를 사용하면보다 효율적이고 반응이 좋은 코드를 작성할 수 있습니다.

PHP 커뮤니티는 개발자 성장을 돕기 위해 풍부한 자원과 지원을 제공합니다. 1) 자료에는 공식 문서, 튜토리얼, 블로그 및 Laravel 및 Symfony와 같은 오픈 소스 프로젝트가 포함됩니다. 2) 지원은 StackoverFlow, Reddit 및 Slack 채널을 통해 얻을 수 있습니다. 3) RFC에 따라 개발 동향을 배울 수 있습니다. 4) 적극적인 참여, 코드에 대한 기여 및 학습 공유를 통해 커뮤니티에 통합 될 수 있습니다.

PHP와 Python은 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1.PHP는 간단한 구문과 높은 실행 효율로 웹 개발에 적합합니다. 2. Python은 간결한 구문 및 풍부한 라이브러리를 갖춘 데이터 과학 및 기계 학습에 적합합니다.

PHP는 죽지 않고 끊임없이 적응하고 진화합니다. 1) PHP는 1994 년부터 새로운 기술 트렌드에 적응하기 위해 여러 버전 반복을 겪었습니다. 2) 현재 전자 상거래, 컨텐츠 관리 시스템 및 기타 분야에서 널리 사용됩니다. 3) PHP8은 성능과 현대화를 개선하기 위해 JIT 컴파일러 및 기타 기능을 소개합니다. 4) Opcache를 사용하고 PSR-12 표준을 따라 성능 및 코드 품질을 최적화하십시오.

PHP의 미래는 새로운 기술 트렌드에 적응하고 혁신적인 기능을 도입함으로써 달성 될 것입니다. 1) 클라우드 컴퓨팅, 컨테이너화 및 마이크로 서비스 아키텍처에 적응, Docker 및 Kubernetes 지원; 2) 성능 및 데이터 처리 효율을 향상시키기 위해 JIT 컴파일러 및 열거 유형을 도입합니다. 3) 지속적으로 성능을 최적화하고 모범 사례를 홍보합니다.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.
