downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Увод> <Разширения за променливи и типове
[edit] Last updated: Fri, 18 Sep 2009

view this page in

Масиви

  • Увод
  • Инсталиране/Конфигуриране
  • Предварително-дефинирани константи
  • Sorting Arrays
  • Функции за работа с масиви
    • array_change_key_case — Променя всички ключове на масив
    • array_chunk — Разделя масив на части
    • array_combine — Създава масив като използва един масив за ключовете и друг за техните стойности
    • array_count_values — Изчислява броя на всички стойности на даден масив
    • array_diff_assoc — Изчислява разлика на масиви с допълнителна проверка на индекса
    • array_diff_key — Изчислява разлика на масиви използювайки ключовете за сравнение
    • array_diff_uassoc — Изчислява разлика на масиви с допълнителна проверка на индекса извършвана от потребителска функция за обратно извикване
    • array_diff_ukey — Изчислява разлика на масиви използювайки потребителска функция за обратно извикване за сравнение на ключовете
    • array_diff — Изчислява разлика на масиви
    • array_fill_keys — Запълва стойностите на указаните ключове на масив
    • array_fill — Запълва масив с дадени стойности
    • array_filter — Филтрира елементите на масив посредством функция за обратно извикване
    • array_flip — Разменя местата на ключовете и стойностите в масив
    • array_intersect_assoc — Изчислява сечението на масиви с проверка на индекса
    • array_intersect_key — Изчислява сечението на масиви използвайки ключовете при сравнението
    • array_intersect_uassoc — Изчислява сечението на масиви с проверка на индекса, сравнявайки индексите посредством функция за обратно извикване
    • array_intersect_ukey — Изчислява сечението на масиви използвайки функция за обратно извикване върху ключовете при сравнението
    • array_intersect — Изчислява сечението на масиви
    • array_key_exists — Проверява присъства ли в масива указания ключ или индекс
    • array_keys — Връща всички ключове на даден масив
    • array_map — Прилага функция за обратно извикване към елементите на дадените масиви
    • array_merge_recursive — Слива един или повече масива рекурсивно
    • array_merge — Слива един или повече масива
    • array_multisort — Sort multiple or multi-dimensional arrays
    • array_pad — Pad array to the specified length with a value
    • array_pop — Премахва последния елемент на масив
    • array_product — Изчислява произведението на стойностите на даден масив
    • array_push — Добавя един или няколко елемента в края на масива
    • array_rand — Връща една или няколко случайни стойности на масив
    • array_reduce — Iteratively reduce the array to a single value using a callback function
    • array_replace_recursive — Replaces elements from passed arrays into the first array recursively
    • array_replace — Replaces elements from passed arrays into the first array
    • array_reverse — Връща масив с елементите в обратен ред
    • array_search — Searches the array for a given value and returns the corresponding key if successful
    • array_shift — Извлича първият елемент на масив
    • array_slice — Extract a slice of the array
    • array_splice — Remove a portion of the array and replace it with something else
    • array_sum — Изчислява сумата на стойностите на масив
    • array_udiff_assoc — Изчислява разлика на масиви с допълнителна проверка на индекса, сравнявайки данните посредством функция за обратно извикване
    • array_udiff_uassoc — Изчислява разлика на масиви с допълнителна проверка на индекса, сравнявайки данните и индексите посредством функция за обратно извикване
    • array_udiff — Изчислява разлика на масиви посредством функция за обратно извикване за сравнение на данните
    • array_uintersect_assoc — Изчислява сечението на масиви с допълнителна проверка на индекса, сравнявайки данните посредством функция за обратно извикване
    • array_uintersect_uassoc — Изчислява сечението на масиви с допълнителна проверка на индекса, сравнявайки данните и индексите посредством функция за обратно извикване
    • array_uintersect — Изчислява сечението на масиви, сравнявайки данните посредством функция за обратно извикване
    • array_unique — Премахва дублираните стойности в масив
    • array_unshift — Добавя един или повече елементи в началото на масив
    • array_values — Връща всички стойности на даден масив
    • array_walk_recursive — Прилага рекурсивно потребителска функция към всеки елемент на даден масив
    • array_walk — Прилага потребителска функция към всеки елемент на даден масив
    • array — Създава масив
    • arsort — Подрежда масив в обратен ред, запазвайки връзката между ключовете и стойностите
    • asort — Подрежда масив, запазвайки връзката между ключовете и стойностите
    • compact — Създава масив, съдържащ имената на променливите и техните стойности
    • count — Връща броя на елементите на даден масив или броя на свойствата на даден обект
    • current — Връща текущия елемент на масива
    • each — Връща текущата двойка ключ/стойност на масива и премества указателя му
    • end — Установява вътрешния указател на масива на последния му елемент
    • extract — Вмъква променливи от масив в текущата символна таблица
    • in_array — Проверява дали дадена стойност съществува в масив
    • key — Връща ключ на масив
    • krsort — Сортира масив по ключ в обратен ред
    • ksort — Сортира масив по ключ
    • list — Установява променливи от списък със стойности, както при масивите
    • natcasesort — Сортира масив, използвайки нечувствителен към регистъра алгоритъм "natural order"
    • natsort — Сортира масив, използвайки алгоритъма "natural order"
    • next — Премества вътрешния указател на масива с една позиция напред
    • pos — Псевдоним на current
    • prev — Премества вътрешния указател на масива с една позиция назад
    • range — Създава масив, съдържащ диапазон от елементи
    • reset — Установява вътрешния указател на масива на първия му елемент
    • rsort — Сортира масив в обратен ред
    • shuffle — Разбърква масив
    • sizeof — Псевдоним на count
    • sort — Сортира масив
    • uasort — Сортира масив използвайки потребителска функция за сравнение, като запазва индексите
    • uksort — Сортира масив по ключовете, използвайки потребителска функция за сравнение
    • usort — Сортира масив по стойностите, използвайки потребителска функция за сравнение


add a note add a note User Contributed Notes Масиви
fo dot q dot who at gmail dot com 06-Apr-2011 04:37
Just another way to pass a multidimensional php array to a js array, but i think a cool one so I decided to put this on here.

<?php

function array_print($item, $key, $array_name)
{
    if(
is_array($item)){
       
$array_name = $array_name."['".$key."']";
        echo
$array_name ."= Array();". "";
       
php_array_to_js_array($item, $array_name);
    }else{
        echo
$array_name."['".$key."'] = \"".$item."\";";
    }
}

function
php_array_to_js_array($array, $array_name){
   
array_walk($array, 'array_print', $array_name);
}

?>
<script type="text/javascript" defer="defer">
<?php
       
echo "js_array = Array();";
       
php_array_to_js_array($array, "js_array");
       
?>
</script>

there is not much to say about that, its simple and understandable, i think... if not just email me. Have a nice day pplz !!

Patrick F.
info at curtinsNOSPAMcreations dot com 05-Nov-2010 07:49
Another way to create a multidimensional array that looks a lot cleaner is to use json_decode.  (Note that this probably adds a touch of overhead, but it sure does look nicer.)  You can of course add as many levels and as much formatting as you'd like to the string you then decode.  Don't forget that json requires " around values, not '!!  (So, you can't enclose the json string with " and use ' inside the string.)

As an example:

<?php
    $myarray
['blah'] = json_decode('[
        {"label":"foo","name":"baz"},
        {"label":"boop","name":"beep"}
    ]'
,true);

print_r($myarray)
?>
returns:

Array
(
    [blah] => Array
        (
            [0] => Array
                (
                    [label] => foo
                    [name] => baz
                )
 
            [1] => Array
                (
                    [label] => boop
                    [name] => beep
                )
        )
)
dragos dot rusu at NOSPAM dot bytex dot ro 07-Mar-2010 06:15
If an array item is declared with key as NULL, array key will automatically be converted to empty string '', as follows:

<?php
$a
= array(
   
NULL => 'zero',
   
1    => 'one',
   
2    => 'two');

// This will show empty string for key associated with "zero" value
var_dump(array_keys($a));

// Array elements are shown
reset($a);
while(
key($a) !== NULL )
{
  echo
key($a) . ": ".current($a) . "<br>";// PHP_EOL
 
next($a);
}

// Array elements are not shown
reset($a);
while(
key($a) != NULL ) // '' == null   => no iteration will be executed
{
  echo
key($a) . ": ".current($a) . "<br>";// PHP_EOL
 
next($a);
}
John Marc 15-Feb-2010 01:30
Be careful when adding elements to a numeric array.
I wanted to store some info about some items from a database and decided to use the record id as a key.

<?php
$key
=3000000000;
$DATA[$key]=true;
?>

This will create an array of 30 million elements and chances are, you will use up all memory with these 2 lines

<?php
$key
=3000000000;
$DATA["$key"]=true;
?>

This on the other hand will force the array to be an associative array and will only create the one element
sunear at gmail dot com 04-Aug-2009 10:45
Made this function to delete elements in an array;

<?php

function array_del_elm($input_array, $del_indexes) {
    if (
is_array($del_indexes)) {
       
$indexes = $del_indexes;
    } elseif(
is_string($del_indexes)) {
       
$indexes = explode($del_indexes, " ");
    } elseif(
is_numeric($del_indexes)) {
       
$indexes[0] = (integer)$del_indexes;
    } else return;
   
$del_indexes = null;
   
   
$cur_index = 0;
    if (
sort($indexes)) for($i=0; $i<count($input_array); $i++) {
        if (
$i == $indexes[$cur_index]) {
           
$cur_index++;
            if (
$cur_index == count($indexes)) return $output_array;
            continue;
        }
       
$output_array[] = $input_array[$i];
    }
    return
$output_array;
}

?>

but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:

<?php

function array_del_elm($target_array, $del_indexes) {
    if (
is_array($del_indexes)) {
       
$indexes = $del_indexes;
    } elseif(
is_string($del_indexes)) {
       
$indexes = explode($del_indexes, " ");
    } elseif(
is_numeric($del_indexes)) {
       
$indexes[0] = (integer)$del_indexes;
    } else return;
    unset(
$del_indexes);
   
    for(
$i=0; $i<count($indexes); $i++) {
        unset(
$target_array[$indexes[$i]]);
    }
    return
$target_array;
}

?>

Fast, compliant and functional ;)
Tyler Bannister 11-Jun-2009 06:59
To delete an individual array element use the unset function

For example:

<?PHP
    $arr
= array( "A", "B", "C" );
    unset(
$arr[1] );
   
// now $arr = array( "A", "C" );
?>

Unlink is for deleting files.
thomasdecaux at ebuildy dot com 15-May-2009 01:14
To browse a simple array:

<?php

foreach ($myArray AS $myItem)
{

}

?>

To browse an associative array:

<?php

foreach ($myArray AS $key=>$value)
{

}

?>

http://www.ebuildy.com
macnimble at gmail dot com 27-Mar-2009 06:59
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can 'stack' an array in one pass, using one loop, like this:

<?php
# array_stack()
# Original idea from:
# http://www.ideashower.com/our_solutions/
#   create-a-parent-child-array-structure-in-one-pass/
function array_stack (&$a, $p = '@parent', $c = '@children')
{
 
$l = $t = array();
  foreach (
$a AS $key => $val):
    if (!
$val[$p]) $t[$key] =& $l[$key];
    else
$l[$val[$p]][$c][$key] =& $l[$key];
   
$l[$key] = (array)$l[$key] + $val;
  endforeach;
  return
$a = array('tree' => $t, 'leaf' => $l);
}

# Example:
$node = array();
$node[1] = array('@parent' => 0, 'title' => 'I am node 1.');
#     ^-----------------------v Link @parent value to key.
$node[2] = array('@parent' => 1, 'title' => 'I am node 2.');
$node[3] = array('@parent' => 2, 'title' => 'I am node 3.');
$node[4] = array('@parent' => 1, 'title' => 'I am node 4.');
$node[5] = array('@parent' => 4, 'title' => 'I am node 5.');

array_stack($node);

$node['leaf'][1]['title'] = 'I am node one.';
$node['leaf'][2]['title'] = 'I am node two.';
$node['leaf'][3]['title'] = 'I am node three.';
$node['leaf'][4]['title'] = 'I am node four.';
$node['leaf'][5]['title'] = 'I am node five.';

echo
'<pre>',print_r($node['tree'],TRUE),'</pre>';
?>

Note that there's no parameter checking on the array value, but this is only to keep the function size small. One could easily a quick check in there to make sure the $a parameter was in fact an array.

Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.
andyd273 at gmail dot com 24-Feb-2009 01:12
A small correction to Endel Dreyer's PHP array to javascript array function. I just changed it to show keys correctly:

            function array2js($array,$show_keys)
            {
                $dimensoes = array();
                $valores = array();
              
                $total = count ($array)-1;
                $i=0;
                foreach($array as $key=>$value){
                    if (is_array($value)) {
                        $dimensoes[$i] = array2js($value,$show_keys);
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    } else {
                        $dimensoes[$i] = '"'.addslashes($value).'"';
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    }
                    if ($i==0) $dimensoes[$i] = '{'.$dimensoes[$i];
                    if ($i==$total) $dimensoes[$i].= '}';
                    $i++;
                }
                return implode(',',$dimensoes);
            }
Endel Dreyer 20-Jan-2009 04:16
Function to convert PHP arrays to JavaScript Array Object:
Useful in some cases.

<?php
function array2js($array,$show_keys=false)
{
   
$dimensoes = array();
   
$valores = array();
   
   
$total = count ($array)-1;
   
$i=0;
    foreach (
$array as $key => $value) {
        if (
is_array($value)) {
           
$dimensoes[$i] = array2js($value,$show_keys);
        } else {
           
$dimensoes[$i] = '"'.addslashes($value).'"';
            if (
$show_keys) '"'.$key.'":'.$dimensoes[$i];
        }
        if (
$i==0) $dimensoes[$i] = '['.$dimensoes[$i];
        if (
$i==$total) $dimensoes[$i].= ']';
       
$i++;
    }
    return
implode(',',$dimensoes);
}
?>
Anonymous 26-Nov-2008 10:36
@jorge at andrade dot cl
This variant is faster:
<?php
function array_avg($array,$precision=2){
    if(!
is_array($array))
        return
'ERROR in function array_avg(): this is a not array';

    foreach(
$array as $value)
        if(!
is_numeric($value))
            return
'ERROR in function array_avg(): the array contains one or more non-numeric values';
   
   
$cuantos=count($array);
  return
round(array_sum($array)/$cuantos,$precision);
}
?>
jorge at andrade dot cl 12-Nov-2008 12:03
To calculate the average of a array

<?php
function array_avg($array,$precision="2"){
   
$a=0;
    if(
is_array($array)){
        foreach(
$array as $value):
            if(!
is_numeric($value)){
               
$a++;
            }
        endforeach;
        if(
$a==0){
           
$cuantos=count($array);
            return
round(array_sum($array)/$cuantos,$precision);
        }else{
            return
"ERROR in function array_avg(): the array contains one or more non-numeric values";
        }       
    }else{
        return
"ERROR in function array_avg(): this is a not array";
    }
}
?>
alan dot lake at lakeinfoworks dot com 22-Oct-2008 08:46
To delete an array key (and its value) from an array:

<?php
   
function array_delete(&$ary,$key_to_be_deleted)
    {
       
$new = array();
        if(
is_string($key_to_be_deleted)) {
            if(!
array_key_exists($key_to_be_deleted,$ary)) {
                return;
            }
            foreach(
$ary as $key => $value) {
                if(
$key != $key_to_be_deleted) {
                   
$new[$key] = $value;
                }
            }
           
$ary = $new;
        }
        if(
is_array($key_to_be_deleted)) {
            foreach(
$key_to_be_deleted as $del) {
               
array_delete(&$ary,$del);
            }
        }
    }
?>
webmaster at infoproducts dot x10hosting dot com 10-Oct-2008 07:13
New value can also be added to the array as shown below.
$theVariable["google"] = "http//google.com";
or
$theVariable["1"] = "http//google.com";
Jack A 07-Oct-2008 08:14
Note that arrays are not allowed in class constants and trying to do so will throw a fatal error.
contact at greyphoenix dot biz 30-Jun-2008 09:36
<?php
//Creating a multidimensional array

$theVariable = array("Search Engines" =>
array (
   
0=> "http//google.com",
   
1=> "http//yahoo.com",
   
2=> "http//msn.com/"),

"Social Networking Sites" =>
array (
   
0 => "http//www.facebook.com",
   
1 => "http//www.myspace.com",
   
2 => "http//vkontakte.ru",)
);

echo
"The first array value is " . $theVariable['Search Engines'][0];
?>

-- Output--
The first array value is http://google.com
applegrew at rediffmail dot com 28-May-2008 08:23
For newbies like me.

Creating new arrays:-
//Creates a blank array.
$theVariable = array();

//Creates an array with elements.
$theVariable = array("A", "B", "C");

//Creating Associaive array.
$theVariable = array(1 => "http//google.com", 2=> "http://yahoo.com");

//Creating Associaive array with named keys
$theVariable = array("google" => "http//google.com", "yahoo"=> "http://yahoo.com");

Note:
New value can be added to the array as shown below.
$theVariable[] = "D";
$theVariable[] = "E";

 
show source | credits | stats | sitemap | contact | advertising | mirror sites