Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

array

(PHP 3, PHP 4, PHP 5)

array --  Создать массив

Описание

array array ( [mixed ...] )

Возвратить массив параметров. Параметры могут быть заданы с индексом при помощи оператора =>. См. раздел руководства array type для ознакомления с понятием массив.

Замечание: array() - это языковая конструкция для представления массивов, а не функция.

Синтакс "index => values", разделённые запятыми, определяет индексы и их значения. Индекс может быть строкой или целым числом. Если индекс опущен, будет автоматически сгенерирован числовой индекс, начиная с 0. Если индекс - число, следующим сгенерированным индексом будет число, равное максимальному числовому индексу + 1. Обратите внимание, что если определены два одинаковых индекса, последующий переназначит предыдущий.

Использование запятой после последнего определённого элемента массива, в отличие от обычного поведения, является приемлемым синтаксисом.

Последующие примеры демонстрируют создание двухмерного массива, определение ключей ассоциативных массивов и и способ генерации числовых индексов для обычных массивов, если нумерация начинается с произвольного числа.

Пример 1. Пример использования array()

<?php
$fruits
= array (
   
"fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
   
"numbers" => array(1, 2, 3, 4, 5, 6),
   
"holes"   => array("first", 5 => "second", "third")
);
?>

Пример 2. Автоматическая индексация array()

<?php
$array
= array(1, 1, 1, 11, 8 => 14 => 1, 19, 3 => 13);
print_r($array);
?>

Результат выполнения данного примера:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Обратите внимание, что индекс '3' определён дважды, и содержит последнее значение 13. Индекс 4 определён после индекса 8, и следующий сгенерированный индекс (значение 19) - 9, начиная с максимального индекса 8.

Этот пример создаёт массив, нумерация которого начинаяется с 1.

Пример 3. array(), нумерация которого начинаяется с 1

<?php
$firstquarter
= array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

Результат выполнения данного примера:

Array
(
    [1] => January
    [2] => February
    [3] => March
)

Как и в Perl, вы имеете доступ к значениям массива внутри кавычек. Однако в PHP нужно заключить ваш массив в фигурные скобки.

Пример 4. Доступ к массиву внутри кавычек

<?php

$foo
= array('bar' => 'baz');
echo
"Hello {$foo['bar']}!"; // Hello baz!

?>

См. также array_pad(), list(), count(), foreach и range().



arsort> <array_walk
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
array
justinbr at andrew dot cmu dot edu
02-Nov-2007 01:20
@Sam Yong - hellclanner [at] live dot com from below:

There's already a range() function - http://us.php.net/manual/en/function.range.php

It's used exactly like yours, plus it can do characters:

<?php
$values
= range(1,1000); //$values = array(1,2,...,1000);
$values = range(100,1); //$values = array(100,99,...,1);
$values = range('a','z'); //$values = array('a','b',...,'z');
?>
Mike Mackintosh
29-Oct-2007 10:38
If you need to add an object as an array key, for example an object from Simple XML Parser, you can use the following.

File.XML
<?xml version="1.0" encoding="UTF-8"?>
<Settings type="General">
  <Setting name="SettingName">This This This</Setting>
</Settings>

The script:
<?php
$raw
= $xml =  new SimpleXMLElement('File.XML');
foreach(
$raw->Setting as $A => $B)
{       
   
// Set Array From XML
   
$Setting[(string) $B['name']] = (string)  $B[0];
}
?>
By telling the key to read the object as a string, it will let you set it.

Hope this helps someone out!
Sam Yong - hellclanner [at] live dot com
27-Oct-2007 05:39
I wanted to put a large range of numbers into an array but it seems to me that the array function don't have that kind of ability for me to put in a range of numbers without having to list down every single number.

Here's my solution:
<?php

function arr_range($r1,$r2){

// the end range is smaller than the start range
// switch around
if($r2 < $r1){
$t = $r1;
$r1 = $r2;
$r2 = $t;
unset(
$t);
}

$return_val = array();
$i = 0;

// for each value of the range
// add the value into the temparory array
for($i = $r1;$i<=$r2;$i++){
$return_val[] = $i;
}

// return the values in array form
return $return_val;
}

// example usages
$values = arr_range(100,6000);
$values = arr_range(1996,2010);
$values = arr_range(50,25); // it works
$values = arr_range(-64,1024);

?>
Christian W.
17-Aug-2007 02:27
If you already created an associative array you can add a new element by:

<?php
$arr
= array("foo" => 1);
print_r($arr);

$arr["bar"] = 2;
print_r($arr);
?>

Output:
Array
(
    [foo] => 1
)
Array
(
    [foo] => 1
    [bar] => 2
)
admin at baungenjar dot com
14-May-2007 06:11
I wrote the code below to load values from a query, than save them to two variables, code and text. It is used to replace values using str_replace.

The tricky part(for me) was building the two variables from a query.

//grab available classes - table of id numbers and //corresponding titles
$class_values = mysql_query($sql_classes);

// grab avaialable book conditions
$condition_values = mysql_query($sql_conditions);

// build conversion tables
// one for class one for coinditoion

    $condcode = array();
    $condtext = array();           
    $classcode = array();
    $classtext = array();
        $i=0;

  while ($row=mysql_fetch_row($condition_values)){
        //echo $row[0]." ".$row[1];
    $condcode[$i] =$row[0];
    $condtext[$i] =$row[1];    
        $i++;    
  }
    $i=0;
  while ($row=mysql_fetch_row($class_values)){
        //echo $row[0]." ".$row[1];
    $classcode[$i] = $row[0];
    $classtext[$i] = $row[1];       
        ++$i;   
  }

// there is no output, but now four arrays exist .
//there are four becuase theycame from two tables
// now i call

//example:
echo str_replace($classcode,$classtext,1);

//would output
Algebra

//
jonovic at seznam dot cz
24-Nov-2006 02:01
Just a short message. There is a problem with array creating with references using function array(). Array is function as any other, so you cannot forse parameters to be passed by reference in call time! This manner is deprecated and you will go into troubles soon with you web provider's php.ini settings.

DO NOT USE!
$my_array = array(&$element_1, &$element_2);

INSTEAD USE!
$my_array[] =& $element_1;
$my_array[] =& $element_2;

This problem should be solved soon since you cannot use many array functions like array_push() etc.
webmaster at phpemailformprocessor dot com
06-Aug-2006 09:48
When using an array to create a list of keys and values for a select box generator which will consist of states I found using "NULL" as an index and ""(empty value) as a value to be useful:

<?php

$states
= array(
   
0    => 'Select a State',
   
NULL => '',
   
1    => 'AL - Alabama',
   
2    => 'AK - Alaska',
   
# And so on ...
);

$select = '<select name="state" id="state" size="1">'."\r\n";

foreach(
$states as $key => $value){
   
$select .= "\t".'<option value="'.$key.'">' . $value.'</option>'."\r\n";
}

$select .= '</select>';

echo
$select;

?>

 This will print out:

<select name="state" id="state" size="1">
    <option value="0">Select a State</option>
    <option value=""></option>
    <option value="1">AL - Alabama</option>
    <option value="2">AK - Alaska</option>
    # And so on ...

</select>

Now a user has a blank value to select if they later decide to not provide their address in the form. The first two options will return TRUE when checked against the php function - EMPTY() after the form is submitted when processing the form
Craig at frostycoolslug dot com
25-Jul-2006 04:39
Just a helpful note, when creating arrays, avoid doing:

<?php
  $var
[key] = "value";
?>

PHP will look for a constant called 'key' before it will treat it as a string, thus slowing down execution (I've seen files with thousands of these and PHP taking over a second to execute).

Always concider switching on E_NOTICE before releasing any PHP, it'll help avoid making simple mistakes.
jupiter at nospam dot com
02-Jun-2006 03:33
<?php

// changes any combination of multiarray elements and subarrays
// into a consistent 2nd level multiarray, tries to preserves keys
function changeMultiarrayStructure($multiarray, $asc = 1) {
  if (
$asc == 1) {  // use first subarrays for new keys of arrays
   
$multiarraykeys = array_reverse($multiarray, true);
  } else { 
// use the last array keys
   
$multiarraykeys = $multiarray// use last subarray keys
 
// end array reordering
 
$newarraykeys = array();  // establish array
 
foreach ($multiarraykeys as $arrayvalue) {  // build new array keys
   
if (is_array($arrayvalue)) {  // is subarray an array
     
$newarraykeys = array_keys($arrayvalue) + $newarraykeys;
    } 
// if count(prevsubarray)>count(currentarray), extras survive
 
// end key building loop
 
foreach ($multiarray as $newsubarraykey => $arrayvalue) {
    if (
is_array($arrayvalue)) {  // multiarray element is an array
     
$i = 0// start counter for subarray key
     
foreach ($arrayvalue as $subarrayvalue) {  // access subarray
       
$newmultiarray[$newarraykeys[$i]][$newsubarraykey] = $subarrayvalue;
       
$i++;  // increase counter
     
// end subarray loop
   
} else {  // multiarray element is a value
     
foreach ($newarraykeys as $newarraykey) {  // new subarray keys
       
$newmultiarray[$newarraykey][$newsubarraykey] = $arrayvalue;
      } 
// end loop for array variables
   
// end conditional
 
// end new multiarray building loop
 
return $newmultiarray;
}

// will change
$old = array('a'=>1,'b'=>array('e'=>2,'f'=>3),'c'=>array('g'=>4),'d'=>5);
// to
$new = array('e'=>array('a'=>1,'b'=>2,'c'=>4,'d'=>5),
 
'f'=>array('a'=>1,'b'=>3,'d'=>5));

// note: if $asc parameter isn't default, last subarray keys used

?>

The new key/value assignment pattern is clearer with bigger arrays.
I use this to manipulate input/output data from my db. Enjoy.
bill at carneyco dot com
02-Feb-2006 08:42
I wanted to be able to control the flow of data in a loop instead of just building tables with it or having to write 500 select statements for single line items. This is what I came up with thanks to the help of my PHP brother in FL. Hope someone else gets some use out it.
<?

//set array variable
$results = array();

//talk to the db
$query = "SELECT * FROM yourtable";
$result = mysql_query($query) or die(mysql_error());

//count the rows and fields
$totalRows = mysql_num_rows($result);
$totalFields = mysql_num_fields($result);

//start the loop
for ( $i = 0; $i < $totalRows; ++$i ) {

//make it 2 dim in case you change your order
  $results[$i] = mysql_fetch_array($result);

//call data at will controlling the loop with the array
echo $results[your_row_id]['your_field_name']; }

//print the entire array to see what lives where
print_r($results);  ?>
php
07-Jan-2006 03:30
This function converts chunks of a string in an array:

function array_str($str, $len) {
  $newstr = '';
  for($i = 0; $i < strlen($str); $i++) {
    $newstr .= substr($str, $i, $len);
  }
  return $newstr;
}

use it as:

$str = "abcdefghilmn";
echo "<table width=\"100%\">\n";
foreach(array_str($str, 4) as $chunk) {
  echo "<tr><td>".$chunk."</td></tr>\n";
}
echo "</table>";

this prints:

------
abcd
------
efgh
------
ilmn
------

It don't use regular expressions. Please add this function to php :)
James
24-Nov-2005 01:04
re: m.izydorski 29-May-2005 07:17

The reason the code snippet below is "very slow" is because the backtick (`) is a shell call delimiter, not a string delimiter. Every element of the array would be executed as a shell call and the result stored as array elements.

<?
// Very slow:
$my_array = array(`sign`, `cat01`, `cat02`, ... , `cat40`,`terra01`, `terra02`, ... , `terra50`);
?>

See the backtick operator page for more information:
http://uk2.php.net/manual/en/language.operators.execution.php
matthiasDELETETHIS at ansorgs dot de
31-May-2005 02:52
How to use array() to create an array of references rather than of copies? (Especially needed when dealing with objects.) I played around somewhat and found a solution: place & before the parameters of array() that shall be references. My PHP version is 4.3.10.

Demonstration:

<?php
$ref1
= 'unchanged';
$ref2 = & $ref1;

$array_of_copies = array($ref1, $ref2);
print_r($array_of_copies); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_copies[0] = 'changed'; // $ref1 = 'changed'; is not equivalent, as it was _copied_ to the array
print_r($array_of_copies); // prints: Array ( [0] => changed [1] => unchanged )

$array_of_refs = array(& $ref1, & $ref2); // the difference: place & before arguments
print_r($array_of_refs); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_refs[0] = 'changed'; // $ref1 = 'changed'; is equivalent as $array_of_refs[0] references $ref1
print_r($array_of_refs, true); // prints: Array ( [0] => changed [1] => changed )
?>
m dot izydorski at anti_spa_m dot rubikon dot pl
29-May-2005 12:17
Ad. rdude's comment

Additionally, there is a performance loss while one are using ` marks instead ' when creating an array:

<?
//Very slow:
$my_array = array(`sign`, `cat01`, `cat02`, ... , `cat40`,`terra01`, `terra02`, ... , `terra50`);

//Much faster:
$my_array = array('sign', 'cat01', 'cat02', ... , 'cat40', 'terra01', 'terra02', ... , 'terra50');
?>

There is no reason to use ` marks (as I know), but this is a default question mark used in query output in phpMyAdmin. If you copy-paste phpMyAdmin query display, you can encounter serious performance problem.
aissatya at yahoo dot com
16-May-2005 01:48
<?php

$foo
= array('bar' => 'baz');
echo
"Hello {$foo['bar']}!"; // Hello baz!

?>
<?php
$firstquarter
= array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
<?php
$fruits
= array (
  
"fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
  
"numbers" => array(1, 2, 3, 4, 5, 6),
  
"holes"  => array("first", 5 => "second", "third")
);
?>
brian at blueeye dot us
21-Apr-2005 05:34
If you need, for some reason, to create variable Multi-Dimensional Arrays, here's a quick function that will allow you to have any number of sub elements without knowing how many elements there will be ahead of time. Note that this will overwrite an existing array value of the same path.

<?php
// set_element(array path, mixed value)
function set_element(&$path, $data) {
    return (
$key = array_pop($path)) ? set_element($path, array($key=>$data)) : $data;
}
?>

For example:

<?php
echo "<pre>";
$path = array('base', 'category', 'subcategory', 'item');
$array = set_element($path, 'item_value');
print_r($array);
echo
"</pre>";
?>

Will display:
Array
(
    [base] => Array
        (
            [category] => Array
                (
                    [subcategory] => Array
                        (
                            [item] => item_value
                        )
                )
        )
)
mortoray at ecircle-ag dot com
18-Feb-2005 05:35
Be careful if you need to use mixed types with a key of 0 in an array, as several distinct forms end up being the same key:

$a = array();
$a[null] = 1;
$a[0] = 2;
$a['0'] = 3;
$a["0"] = 4;
$a[false] = 5;
$a[0.0] = 6;
$a[''] = 7;
$a[] = 8;

print_r( $a );

This will print out only 3 values: 6, 7, 8.
rdude at fuzzelish dot com
17-Feb-2005 01:35
If you are creating an array with a large number of static items, you will find serious performance differences between using the array() function and the $array[] construct. For example:
<?
 // Slower method
 $my_array = array(1, 2, 3,
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
Z058440144362 Z348613067571