PHP의 배열

王林
풀어 주다: 2024-08-29 12:42:53
원래의
488명이 탐색했습니다.

다음 문서인 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. 숫자형 또는 인덱스 배열
  2. 연관배열
  3. 다차원 배열
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의 배열

또는

숫자 배열을 선언하는 다른 방법은 다음 프로그램입니다. 이 프로그램에서는 값을 수정하고 인쇄하는 방법도 살펴보겠습니다.

코드:

<?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);
?>
로그인 후 복사

출력:

PHP의 배열

이제 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>";
}
?>
로그인 후 복사

출력:

PHP의 배열

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>";}
?>
로그인 후 복사

출력:

PHP의 배열

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의 배열

또는

연관배열의 다차원 배열

코드:

<?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의 배열 방법

다음은 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);
?>
로그인 후 복사

출력:

PHP의 배열

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:

PHP의 배열

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:

PHP의 배열

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:

PHP의 배열

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:

PHP의 배열

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:

PHP의 배열

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:

PHP의 배열

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:

PHP의 배열

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
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!