Creating a one-dimensional array of PHP

Source: Internet
Author: User

Mode 1:

<?php
$chicken [0] = 3;
$chicken [1] = 5;
$chicken [2] = 1;
$chicken [3] = 3.4;
$chicken [4] = 2;
$chicken [5] = 50;
?>

For example: There are 6 chickens in a chicken farm, with a weight of 3KG, 5kg,1kg,3.4kg, 2KG and 50KG, which requires that all chickens be recycled and the overall weight and average weight are obtained.

<?php
$chicken [0] = 3;
$chicken [1] = 5;
$chicken [2] = 1;
$chicken [3] = 3.4;
$chicken [4] = 2;
$chicken [5] = 50;
$weight = 0;
$avg = 0;
Traversing an array
for ($i = 0; $i < count ($chicken); $i + +) {
echo "First". ($i + 1). "The weight of a chicken =". $chicken [$i]. ' <br/> ';
$weight + + $chicken [$i];
}
$avg = $weight/count ($chicken);
echo "Total:". Count ($chicken). "Chicken." ' <br/> ';
echo "Overall weight is:". $weight. "<br/>";
echo "Average weight is:". $avg;
?>

Mode 2:

Basic syntax:

$ array name =array (value,......);

$chicker =array (3,5,1,3.4,2,50)

For example: There are 6 chickens in a chicken farm, with a weight of 3KG, 5kg,1kg,3.4kg, 2KG and 50KG, which requires that all chickens be recycled and the overall weight and average weight are obtained. Implemented using the second definition of an array

<?php
$chicken = Array (3, 5, 1, 3.4, 2, 50);
$weight = 0;
$avg = 0;
Traversing an array
for ($i = 0; $i < count ($chicken); $i + +) {
echo "First". ($i + 1). "The weight of a chicken =". $chicken [$i]. ' <br/> ';
$weight + + $chicken [$i];
}
$avg = $weight/count ($chicken);
echo "Total:". Count ($chicken). "Chicken." ' <br/> ';
echo "Overall weight is:". $weight. "<br/>";
echo "Average weight is:". $avg;
?>

Mode 3

By default, array subscripts start at 0. In fact, you can also specify that you can specify keywords within the box number.

At this point, traversing the array requires the use of foreach

Basic syntax:

$arr [' logo ']= "Beijing";

$arr [' abc ']=100;

Cases:

<?php
$arr [' logo '] = "www.bianceng.cn";
$arr [' abc '] = 123;
foreach ($arr as $key => $val) {
Echo $val. ' <br/> ';
}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.