본문 바로가기

PHP

[PHP] 배열

 - PHP 배열 만들기

<!DOCTYPE html>
<html>
<body>

<?php
$cars=array("Volvo","BMW","Toyota"); 
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

</body>
</html>

(예제 출처: PHP Arrays)


(실행 결과)

I like Volvo, BMW and Toyota.



 - PHP 배열의 길이 구하기

<!DOCTYPE html>
<html>
<body>

<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>

</body>
</html>

(예제 출처: PHP Arrays)


(실행 결과)

3



 - PHP 배열과 반복문

<!DOCTYPE html>
<html>
<body>

<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++)
   {
   echo $cars[$x];
   echo "<br>";
   }
?>

</body>
</html>

(예제 출처: PHP Arrays)


(실행 결과)

Volvo
BMW
Toyota



 - PHP 배열과 키 값

<!DOCTYPE html>
<html>
<body>

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

</body>
</html>

(예제 출처: PHP Arrays)


(실행 결과)

Peter is 35 years old.

(같은 결과 다른 소스)

<!DOCTYPE html>
<html>
<body>

<?php
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";

echo "Peter is " . $age['Peter'] . " years old.";
?>

</body>
</html>



 - PHP 배열과 키 값 그리고 반복문

<!DOCTYPE html>
<html>
<body>

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

foreach($age as $x=>$x_value)
   {
   echo "Key=" . $x . ", Value=" . $x_value;
   echo "<br>";
   }
?>

</body>
</html>

(예제 출처: PHP Arrays)


(실행 결과)

Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43



 - PHP 다차원 배열

<!DOCTYPE html>
<html>
<body>

<?php
// A two-dimensional array
$cars = array
   (
   array("Volvo",100,96),
   array("BMW",60,59),
   array("Toyota",110,100)
   );

echo $cars[0][0].": Ordered: ".$cars[0][1].". Sold: ".$cars[0][2]."<br>";
echo $cars[1][0].": Ordered: ".$cars[1][1].". Sold: ".$cars[1][2]."<br>";
echo $cars[2][0].": Ordered: ".$cars[2][1].". Sold: ".$cars[2][2]."<br>";
?>

</body>
</html>

(예제 출처: PHP Multidimensional Arrays)


(실행 결과)

Volvo: Ordered: 100. Sold: 96
BMW: Ordered: 60. Sold: 59
Toyota: Ordered: 110. Sold: 100