Adding entries to a php array. PHP: Adding and removing array elements


There are many functions and operators for converting arrays in PHP: Collection of functions for working with arrays

There are several ways to add an array to an array when php help and all of them can be useful for individual cases.

"Operator +"

This is a simple but insidious way:

$c = $a + $b

This way, only those keys are added that are not already in the $a array. In this case, the elements are appended to the end of the array.

That is, if the key from the array $b is not present in the array $a, then an element with this key will be added to the resulting array.
If the $a array already contains an element with such a key, then its value will remain unchanged.

In other words, changing the places of the terms changes the sum: $a + $b != $b + $a - this is worth remembering.

And now more detailed example to illustrate this:

$arr1 = ["a" => 1, "b" => 2]; $arr2 = ["b" => 3, "c" => 4]; var_export($arr1 + $arr2); //array (// "a" => 1, // "b" => 2, // "c" => 4, //) var_export($arr2 + $arr1); //array (// "b" => 3, // "c" => 4, // "a" => 1, //)

array_merge() function

You can use this function as follows:

$result = array_merge($arr1, $arr2)

It resets numeric indices and replaces string ones. Great for concatenating two or more arrays with numeric indexes:

If the input arrays have the same string keys, then each subsequent value will replace the previous one. However, if the arrays have the same numeric keys, the value mentioned last will not replace the original value, but will be added to the end of the array.

array_merge_recursive function

Does the same thing as array_merge except it recursively goes through each branch of the array and does the same with the children.

array_replace() function

Replaces array elements with elements of other passed arrays.

array_replace_recursive() function

Same as array_replace but processes all branches of the array. Help for array_replace_recursive.

Other functions

There are a number of useful functions for working with arrays in PHP, the existence of which is advisable to know. You can read about them at the link:

array_pad

Adds several elements to the array.
Syntax:

Array array_pad(array input, int pad_size, mixed pad_value)

The array_pad() function returns a copy of the input array to which elements with pad_values ​​have been added, so that the number of elements in the resulting array is pad_size.
If pad_size>0, then the elements will be added to the end of the array, and if<0 - то в начало.
If the pad_size value is less than the elements in the original input array, then no addition will occur and the function will return source array input.
Example of using array_pad() function:

$arr = array(12, 10, 4);
$result = array_pad($arr, 5, 0);
// $result = array(12, 10, 4, 0, 0);
$result = array_pad($arr, -7, -1);
// $result = array(-1, -1, -1, -1, 12, 10, 4)
$result = array_pad($arr, 2, "noop");
// will not add

array_map

Apply a custom function to all elements of the specified arrays.
Syntax:

Array array_map(mixed callback, array arr1 [, array ...])

The array_map() function returns an array that contains the elements of all specified arrays after processing by the user callback function.
The number of parameters passed to the user-defined function must match the number of arrays passed to array_map().

Example of using the array_map() function: Processing a single array

return $n*$n*$n;
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

Array(
=> 1
=> 8
=> 27
=> 64
=> 125
)

Example of using the array_map() function: Processing multiple arrays

return "The number $n in Spanish is $m";
}
function map_Spanish($n, $m) (
return array ($n => $m);
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");
$c = array_map("show_Spanish", $a, $b);
print_r($c);

$d = array_map("map_Spanish", $a , $b);
print_r($d);
?>

The given example will output the following:

// printout of $cArray(
=> Number 1 in Spanish - uno
=> Number 2 in Spanish - dos
=> Number 3 in Spanish - tres
=> Number 4 in Spanish - cuatro
=> Number 5 in Spanish - cinco
)

// printout of $dArray(
=>Array
=> uno
)

=>Array
=> dos
)

=>Array
=> tres
)

=>Array
=> cuatro
)

=>Array
=> cinco
)

Typically the array_map() function is used on arrays that have the same size. If arrays have different lengths, then the smaller ones are padded with elements with empty values.
It should be noted that if you specify null instead of the name of the processing function, an array of arrays will be created.
Example of using the array_map() function: Creating an array of arrays

$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");
$d = array_map(null, $a, $b, $c);
print_r($d);
?>

The given example will output the following:

Array(
=>Array
=> 1
=> one
=> uno
)

=>Array
=> 2
=> two
=> dos
)

=>Array
=> 3
=> three
=> tres
)

=>Array
=> 4
=> four
=> cuatro
)

=>Array
=> 5
=> five
=> cinco
)

Function supported by PHP 4 >= 4.0.6, PHP 5

array_pop

Retrieves and removes the last elements of an array.
Syntax:

Mixed array_pop(array arr);

The array_pop() function pops the last element from the array arr and returns it, removing it afterwards. With this function we can build stack-like structures. If the array arr was empty, or it is not an array, the function returns the empty string NULL.

After using the array_pop() function, the array cursor is set to the beginning.
Example of using array_pop() function:

$fruits = array_pop($stack);
print_r($stack);
print_r($fruits);
?>

The example will output the following:

Array(
=> orange
=> banana
=> apple
)

Function supported by PHP 4, PHP 5

array_push

Adds one or more elements to the end of the array.
Syntax:

Int array_push(array arr, mixed var1 [, mixed var2, ..])

The array_push() function adds elements var1, var2, etc. to the array arr. It assigns numeric indexes to them - exactly as it does for standard .
If you only need to add one element, it might be easier to use this operator:

Array_push($Arr,1000); // call the function$Arr=100; // the same thing, but shorter

Example of using array_push() function:

array_push($stack, "apple", "raspberry");
print_r($stack);
?>

The example will output the following:

Array(
=> orange
=> banana
=> apple
=> raspberry
)

Please note that the array_push() function treats the array as a stack and always adds elements to the end.
Function supported by PHP 4, PHP 5

array_shift

Retrieves and removes the first element of an array.
Syntax:

Mixed array_shift(array arr)

The array_shift() function takes the first element of the array arr and returns it. It is very similar to array_pop(),
but only gets the initial one, not final element, and also produces a rather strong “shake-up” of the entire array: after all, when extracting the first element, you have to adjust all the numeric indices of all remaining elements, because All subsequent elements the array is shifted one position forward. The string array keys do not change.
If arr is empty or not an array, the function returns NULL.

After using this function, the array pointer is moved to the beginning.
Example of using array_shift() function:

$fruit = array_shift($stack);
print_r($stack);
?>

This example will output the following:

Array(
=> banana
=> apple
=> raspberry
)

and the $fruit variable will have the value "orange"

Function supported by PHP 4, PHP 5

array_unshift

Adds one or more values ​​to the beginning of the array.
Syntax:

Int array_unshift(list arr, mixed var1 [,mixed var2, ...])

The array_unshift() function adds the passed var values ​​to the beginning of the arr array. The order of new elements in the array is preserved. All digital indexes of the array will be changed so that it starts from zero. All string indexes of the array are unchanged.
The function returns the new number of elements in the array.
An example of using the array_unshift() function:

array_unshift($queue, "apple", "raspberry");
?>

Now the $queue variable will have the following elements:

Array(
=> apple
=> raspberry
=> orange
=> banana
)

Function supported by PHP 4, PHP 5

array_unique

Removes duplicate values ​​in an array.
Syntax:

Array array_unique(array arr)

The array_unique() function returns an array composed of all the unique values ​​in the array arr along with their keys, by removing all duplicate values. The first key=>value pairs encountered are placed in the resulting array. The indexes are preserved.
An example of using the array_unique() function:

"green", "red", "b" =>
"green", "blue", "red");

print_r($result);
?>

The example will output the following:

Array(
[a] => green
=> red
=> blue
)

Example of using the array_unique() function: Comparing data types

$result = array_unique($input);
var_dump($result);
?>

The example will output the following:

Array(2) (
=> int(4)
=> string(1) "3"
}

Function supported by PHP 4 >= 4.0.1, PHP 5

array_chunk

The function splits the array into parts.
Syntax:

Array array_chunk(array arr, int size [, bool preserve_keys])

The array_chunk() function splits the original array arr into several arrays, the length of which is specified by the number size. If the dimension of the original array is not divisible exactly by the size of the parts, then the final array will have a smaller dimension.
The array_chunk() function returns a multidimensional array, the indices of which start from 0 to the number of resulting arrays, and the values ​​are the arrays obtained as a result of splitting.
Optional parameter preserve_keys specifies whether the keys of the original array should be preserved or not. If this parameter is false (the default value), then the indices of the resulting arrays will be specified by numbers starting from zero. If the parameter is true, then the keys of the original array are preserved.
Example of using array_chunk() function:

$array = array("1st element",
"2nd element"
"3rd element"
"4th element"
"5th element");
print_r(array_chunk($array, 2));
print_r(array_chunk($array, 2, TRUE));

The example will output the following:

Array(
=>Array
=> 1st element
=> 2nd element
)

=>Array
=> 3rd element
=> 4th element
)

=>Array
=> 5th element
)

)
Array(
=>Array
=> 1st element
=> 2nd element
)

=>Array
=> 3rd element
=> 4th element
)

=>Array
=> 5th element
)

Function supported by PHP 4 >= 4.2.0, PHP 5

array_fill

The function fills the array with specific values.
Syntax:

Array array_fill(int start_index, int num, mixed value)

The array_fill() function returns an array containing the values ​​specified in the value parameter of size num, starting with the element specified in the start_index parameter.
Example of using array_diff_uassoc():

print_r($a);
?>

The example will output the following:

Array(
=> banana
=> banana
=> banana
=> banana
=> banana
=> banana
)

Function supported by PHP 4 >= 4.2.0, PHP 5

array_filter

The function applies a filter to an array using a custom function.
Syntax:

Array array_filter(array input [, callback callback])

The array_filter() function returns an array that contains the values ​​found in the input array, filtered according to the results of the user-defined callback function.
If the input array is an associative array, the indices are preserved in the resulting array.
Example of using array_filter() function:

return ($var % 2 == 1);
}

function even($var) (
return ($var % 2 == 0);
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);
echo "Odd:n";
print_r(array_filter($array1, "odd"));
echo "Even:n";
t_r(array_filter($array2, "even"));
?>

The example will output the following:

Odd:Array(
[a] => 1
[c] => 3
[e] => 5
Even:Array(
=> 6
=> 8
=> 10
=> 12
)

It is worth noting that instead of the name of the filtering function, you can specify an array that contains a reference to the object and the name of the method.
It is also worth noting that when processing an array with the array_filter() function, it cannot be changed: add, remove elements or reset the array, because this may lead to incorrect operation of the function.
Function supported by PHP 4 >= 4.0.6, PHP 5

date: 2010-07-09

First of all, let's create an array. Let there be an array individual cards same suit (spades = s). Let's call him var cards.

Var cards = ["8s","9s","Ts","Js","Qs"]; // 5 elements (cards of the same suit from 8 to queen)

As you can see, there are 5 elements in our array, each of which has its own unique index. Let us remind you once again that indexing of array elements starts from 0, do not forget about this, i.e. in our example, the first element of the array ("8s") is 0, the last ("Qs") is 4.

Adding an element to the end of an array

Knowing that in our array var cards there are only 5 elements and the last index ends with 4, then we can add new element into an array like this:

Var cards = ["8s","9s","Ts","Js","Qs"]; // 5 elements (cards of the same suit from 8 to queen) cards = "Ks"; //added a new element to the end of the array, now there are 6 elements in the array

The difficulty with this approach is that if the array contains many elements, counting them can be very inconvenient. For such cases there is a simpler solution - the array property length, which determines the length of the array, i.e. number of elements in the array. Let's see an example:

Launch! var cards = ["8s","9s","Ts","Js","Qs"]; // 5 elements (cards of the same suit from 8 to queen) cards = "Ks"; /* add a new element to the array using the lenght property */ for(i = 0; i

In line 4 of our code we added an entry in the form cards;. This code is identical cards;, since the property length, as mentioned above, determines the number of all elements in the array. In other words, we don’t need to count the elements, instead we write the array itself, put a dot and apply keyword length. On line 7 we also apply the property length- first we determine the start of the counter from 0, then there is a condition in which we write that if the counter value is less than the length of the array, then we increase the counter by one and execute the code in curly braces(in the body of the loop), where we display array elements using the alert() command, you can use document.write(). In other words, everything looks like this:
0 is less than 6? Yes, less. We increase the counter by 1 and execute the code in the body of the loop
1 is less than 6? Yes, less. We increase the counter by 1 and execute the code in the body of the loop
2 is less than 6? Yes, less. We increase the counter by 1 and execute the code in the body of the loop
.....................................................
Is 6 less than 6? No. The cycle stops.

push() method

In addition to the methods described above, there is also a method push(), with which we can add any type of data, and even a variable, to the end of the array. In this case, there can be several elements at once, which are written separated by commas in parentheses. Let's look at an example:

Launch! var cards = ["8s","9s","Ts","Js","Qs"]; // 5 elements (cards of the same suit from 8 to queen) cards.push("Ks","As"); /* add new elements to the array using the push() method */ for(i = 0; i

Adding an element to the beginning of an array

unshift() method

If you need to add elements at the very beginning of the array, use the method unshift. It works on the same principle as the push() method.

Launch! var cards = ["8s","9s","Ts","Js","Qs"]; // 5 elements (cards of the same suit from 8 to queen) cards.unshift("5s","6s","7s"); /* add new elements to the array using the unshift() method */ for(i = 0; i

In this chapter:

An array is a special type of variable that stores many data elements. An array allows you to access separately any of its constituent elements (since they are stored separately inside the array), and it is also possible to copy or process the entire array.

PHP arrays are untyped, meaning that array elements can be of any type, and different elements in the array can have Various types. In addition, PHP arrays are dynamic, which means that there is no need to declare a fixed size and new elements can be added at any time.

Array Basics

To work with arrays, you need to learn two new concepts: elements and indices. Elements are values ​​stored in an array; the values ​​can be of absolutely any type. Each element can be accessed by its unique index. The index can be an integer or a string.

Arrays can be divided into two types: index, in which only an integer is used as the index value, and associative, where the index value can be either a string or a number. Often in associative arrays the index is called: “key”.

Index arrays are usually called simply "arrays", and associative arrays are called "hashes", "associative" or "dictionaries".

Creating an Array

There are three ways to create arrays in PHP. The first way is to create it using the special array() function. The function takes as arguments any number of key => value pairs separated by commas or just values ​​also separated by commas. It returns an array that can be assigned to a variable.

Since you don't have to specify a key, values ​​can be added to the array without specifying one. If a key is not specified, PHP will use numeric indexes. By default, elements will be numbered starting from zero. Arrays with numeric indexes allow you to simply add an element, and PHP will automatically use the previous largest integer key value incremented by 1.

You can also specify the key for individual elements:

"c", "d"); var_dump($my_array); ?>

When you run this example, you may notice that the last element ("d") was assigned to the key 8 . It happened this way because the most great importance there was a whole type of key in front of him 7 .

Now let's look at creating an associative array using the array() function. Associative Array it is written a little differently: to add an element, the format key => value is used.

"30", "February" => "28/29 (29 happens every four years)", "March" => "31", "April" => "30", "May" => "31", " June" => "30", "July" => "31", "August" => "31", "September" => "30", "October" => "31", "November" => " 30", "December" => "31"); ?>

With the indentation you see in this example, it is easier to add elements to the array than when they are written on one line.

Now let's look at the second way to create an array: using square brackets, instead of the special array() function:

"bar", "bar" => "foo"); // another way to create an array $my_array = ["foo" => "bar", "bar" => "foo"]; ?>

There is no difference between these arrays, except for the difference in spelling.

Please note that in PHP arrays can contain keys int types and string at the same time, i.e. PHP doesn't differentiate between indexed and associative arrays.

"bright", "wheel" => "round", 10 => "house", -5 => 290]; ?>

Note: When choosing a name for an array, be careful not to use a name that is the same as another variable, since they share a common namespace. Creating a variable with the same name as an existing array will delete the array without producing any warnings.

The third way to create arrays will be discussed in the “Adding and Removing Array Elements” section.

Index Conversion

As mentioned at the very beginning of the chapter, a key can be one of two types: string or integer. Therefore, keys that do not match one of these types will be converted:

  • If the key is a string that contains a number, it will be converted to type integer. However, if the number is an invalid decimal integer, such as "09", then it will not be converted to an integer.
  • Real number(float) will also be converted to integer - fraction in this case it is discarded. For example, if the key value is 5.4, it will be interpreted as 5.
  • The boolean type (bool) will also be converted to integer. For example, if the key value is true, then it will be converted to 1, and the key with the value false will be converted to 0 accordingly.
  • If type null is used, it will be converted to the empty string.
  • Objects and arrays cannot be used as keys.

If multiple elements in an array declaration use the same key, then only the last one will be used and all others will be overwritten.

"a", "1" => "b", // keys are converted to number 1 1.5 => "c", true => "d"); var_dump($my_array); ?>

In the example given, all keys will be converted to one, based on this, the array will contain only one element, the contents of which will be overwritten 3 times, as a result, its value will become "d".

Accessing Array Elements

Array elements are accessed using square brackets that indicate the index/key: array.

"milk", 2 => "foo"); echo $my_array["Chocolate"], "
"; echo $my_array; ?>

Another way to access array elements is to use direct array dereference.

hello world! ?>

This example shows that you can access the index of an array returned as the result of a function or method call.

Adding and Removing Array Elements

Now that you have the basic concepts of arrays, let's look at ways to write values ​​to an array. An existing array can be modified by explicitly setting values ​​in it. This is done by assigning values ​​to an array.

The operation of assigning a value to an array element is the same as the operation of assigning a value to a variable, except for the square brackets () that are added after the array variable name. IN square brackets the index/key of the element is indicated. If no index/key is specified, PHP will automatically select the smallest unoccupied numeric index.

"zero", 1 => "one"); $my_arr = "two"; $my_arr = "three"; var_dump($my_arr); // assignment without specifying the index/key $my_arr = "four"; $my_arr = "five"; echo "
"; var_dump($my_arr); ?>

To change a specific value, you simply assign a new value to an existing element. To remove any element of an array with its index/key or to completely remove the array itself, use the unset() function:

Note: As mentioned above, if an element is added to an array without specifying a key, PHP will automatically use the previous largest integer key value increased by 1. If there are no integer indexes in the array yet, then the key will be 0 (zero).

Note that the largest integer value of the key does not necessarily exist in the array in this moment , this may be due to the removal of array elements. After elements have been removed, the array is not reindexed. Let's give next example to make it clearer:

"; print_r($my_arr); // Add the element (note that the new key will be 3 instead of 0). $my_arr = 6; echo "
"; print_r($my_arr); // Do reindexing: $my_arr = array_values($my_arr); $my_arr = 7; echo "
"; print_r($my_arr); ?>

This example used two new functions, print_r() and array_values(). The array_values() function returns an indexed array (re-indexes the returned array with numeric indices), and the print_r function works like var_dump, but outputs arrays in a more readable form.

Now we can look at the third way to create arrays:

The example showed a third way to create an array. If the $weekdays array has not yet been created, it will be created. However, this type of array creation is not recommended because if the $weekdays variable has already been created and contains a value, it may cause unexpected results from the script.

If you have any doubts about whether array variable, use the function is_array. For example, the check can be done as follows:

"; $no = "regular string"; echo is_array($no) ? "Array" : "Not an array"; ?>

Looping through an array

Operator foreach loop performs a sequential search of all elements of the array. It only works with arrays and objects, and if used with variables of other types or uninitialized variables, an error will be generated. There are two types of syntax for of this cycle. The first kind of syntax looks like this:

Foreach ($array as $value) (instructions)

The loop will iterate over the given array - $array (the name of the array is substituted for $array). At each iteration, the value of the current element is assigned to the variable $value (you can specify any other variable name). The foreach loop operator is very convenient because it itself loops through and reads all the elements of the array until the last one is reached. It allows you to avoid constantly remembering the fact that array indexing starts from zero and never goes beyond the array, which makes the loop construction very convenient and helps to avoid common mistakes. Let's see how it works with an example:

The second type of foreach syntax looks like this:

Foreach ($array as $key => $value) (instructions)

When using this form of syntax, at each iteration the value of the current key is additionally assigned to the variable $key (you can specify any other variable name):

$value) ( ​​echo "[$key] => ", $value, "
"; } ?>

To be able to directly change array elements within a loop, you need to use a reference. In this case, the value will be assigned by reference.

Note: The reference to the last element of the array remains even after the foreach statement has completed. Therefore, it is recommended to remove it using the unset() function as shown in the example above. Let's see what happens if we don't use unset():"; foreach ($numbers as &$num) ( echo $num, " "; ) ?> One thing to note is that the reference can only be used if the array being iterated is a variable. The following code will not work:

Let's look at ways to write values ​​to an array. An existing array can be modified by explicitly setting values ​​in it. This is done by assigning values ​​to an array.

The operation of assigning a value to an array element is the same as the operation of assigning a value to a variable, except for the square brackets () that are added after the array variable name. The index/key of the element is indicated in square brackets. If no index/key is specified, PHP will automatically select the smallest unoccupied numeric index.

"zero", 1 => "one"); $my_arr = "two"; $my_arr = "three"; var_dump($my_arr); // assignment without specifying the index/key $my_arr = "four"; $my_arr = "five"; echo "
"; var_dump($my_arr); ?>

To change a specific value, you simply assign a new value to an existing element. To remove any element of an array with its index/key or completely remove the array itself, use the unset() function:

Note: As mentioned above, if an element is added to an array without specifying a key, PHP will automatically use the previous largest integer key value increased by 1. If there are no integer indexes in the array yet, then the key will be 0 (zero).

Note that the largest integer value of the key does not necessarily exist in the array at the moment, this may be due to the removal of array elements. After elements have been removed, the array is not reindexed. Let's take the following example to make it clearer:

"; print_r($my_arr); // Add the element (note that the new key will be 3 instead of 0). $my_arr = 6; echo "
"; print_r($my_arr); // Do reindexing: $my_arr = array_values($my_arr); $my_arr = 7; echo "
"; print_r($my_arr); ?>

This example used two new functions, print_r() and array_values(). The array_values() function returns an indexed array (re-indexes the returned array with numeric indices), and the print_r function works like var_dump but outputs arrays in a more readable form.

Now we can look at the third way to create arrays:

The example showed a third way to create an array. If the $weekdays array has not yet been created, it will be created. However, this type of array creation is not recommended because if the $weekdays variable has already been created and contains a value, it may cause unexpected results from the script.

If you are in doubt about whether a variable is an array, use the is_array function. For example, the check can be done as follows:

"; $no = "regular string"; echo is_array($no) ? "Array" : "Not an array"; ?>







2024 gtavrl.ru.