Add new item to php array. PHP: Adding and Removing Array Elements. Defining elements in an array
Adding items to an array
If the array exists, additional elements can be added to it. This is done directly using the assignment operator (equal sign) in the same way as assigning a value to a string or number. In this case, you do not need to set the key of the added element, but in any case, when accessing the array, you need square brackets... By adding two new items to the $ List, we write:
$ List = "pears";
$ List = "tomatoes";
If no key is specified, each element will be added to the existing array and indexed with the next sequential number. If we add new elements to the array from the previous section, whose elements had indexes 1, 2 and 3, then pears will have index 4, and tomatoes will have 5. When you explicitly set the index, and the value with it is already exists, then the existing value in this place will be lost and replaced by a new one:
$ List = "pears";
$ List = "tomatoes";
Now the value of the element at index 4 is "tomatoes" and the element "oranges" is no longer there. I would advise not to specify a key when adding elements to an array, unless, of course, you want to specifically overwrite any existing data. However, if strings are used as indices, the keys must be specified so as not to lose values.
We will try to add new elements to the array by rewriting the soups.php script. First, by printing the original elements of the array, and then the original ones along with the added ones, we can easily see the changes that have occurred. Just as you can find out the length of a string (the number of characters it contains) using the strlen () function, it is also easy to determine the number of elements in an array using the count () function:
$ HowMany = count ($ Array);
- Open the soups.php file in text editor.
- After initializing the array with the array () function, add the following entry: $ HowMany = count ($ Soups);
- Add three additional elements to the array. $ Soups ["Thursday"] = "Chicken Noodle";
- Recalculate the elements in the array and print this value. $ HowManyNow = count ($ Soups);
- Save the script (Listing 7.2), upload it to the server, and test it in a browser (Figure).
print ("The array contains $ HowMany elements.
\ n ");
The count () function will determine how many elements are in the $ Soups array. By assigning this value to a variable, you can print it.
$ Soups ["Friday"] = "Tomato";
$ Soups ["Saturday"] = "Cream of Broccoli";
print ("The array now contains $ HowManyNow elements.
\ n ");
Listing 7.2 You can directly add one element at a time to an array by assigning a value to each element using the appropriate operator. The count () function can be used to find out how many elements are in the array.
1
2
3
4
5 6 $ Soups = array (
7 "Monday" => "Clam Chowder",
8 "Tuesday" => "White Chicken Chili",
9 "Wednesday" => "Vegetarian");
11 print ("The array contains $ HowMany
elements.
\ n ");
12 $ Soups ["Thursday"] = "Chicken Noodle";
13 $ Soups ["Friday"] = "Tomato";
14 $ Soups ["Saturday"] = "Cream of
Broccoli ";
15 $ HowManyNow = count ($ Soups);
16 print ("The array now contains
$ HowManyNow elemente.
\ n ");
17 ?>
18
19
PHP 4.0 introduced new function, allowing you to add one array to another. This operation can also be called merging or concatenating arrays. The array_merge () function is called like this:
$ NewArray = array_merge ($ OneArray, $ TwoArray);
You can rewrite the soups.php page using this function if you are using a server with PHP 4.0 installed.
Combining two arrays
- Open the soups.php file in a text editor if it is not already open.
- After initializing the $ Soups array, count its elements and print the result. $ HowMany = count ($ Soups);
- Concatenate the two arrays into one. $ TheSoups = array_merge ($ Soups, $ Soups2);
- Count the elements of the new array and print the result. $ HowMany3 = count ($ TheSoups);
- Close the PHP and HTML document. ?>
- Save the file (Listing 7.3), upload it to the server, and test it in a browser (Figure).
print ("The $ Soups array contains $ HowMany elements.
\ n ");
- Create a second array, count its elements, and print the result as well.
"Thursday" => "Chicken Noodle",
"Friday" => "Tomato",
"Saturday" => "Cream of Broccoli");
$ HowMany2 = count ($ Soups2);
print ("The $ Soups2 array contains $ HowMany2 elements.
\ n ");
Make sure that the arrays are in this order ($ Soups, then $ Soups2), that is, Thursday and Friday elements should be added to Wednesday's Monday elements, and not vice versa.
print ("The $ TheSoups array contains
- $ HowMany3 elements.
\ n ");
Listing 7.3 The Array_merge () function is new. This is one of several additional PHP 4.0 functions for working with arrays. Using arrays can save you a lot of time.
1
2
3
4
5 6 $ Soups = array!
7 "Monday" => "Clam Chowder",
"Tuesday" => "White Chicken Chili",
8 "Wednesday" => "Vegetarian"
9);
10 $ HowMany = count ($ Soups);
11 print ("The $ Soups array contains $ HowMany elements.
\ n ");
12 $ Soups2 = array (
13 "Thursday" => "Chicken Noodle",
14 "Friday" => "Tomato",
15 "Saturday" => "Cream of Broccoli"
16); .
17 $ HowMany2 = count ($ Soups2);
18 print ("The $ Soups2 array contains $ HowMany2 elements.
\ n ");
19 $ TbeSoupe = array_merge ($ Soups, $ Soups2);
20 $ HowMany3 = count ($ TheSoups);
21 print ("The $ TheSoups array contains. $ HowMany3 elements.
\ n ");
22 ?> "
23
24
Be careful when adding elements to the array directly. The correct way to do this is: $ Ar ray = "Add This"; $ Aggau = "Add This"; but it’s correct like this: $ Aggau = "Add This" ;. If you forget to put parentheses, then the added value will destroy the existing array, turning it into a simple string or number.
PHP 4.0 has several new functions for working with arrays. Not all of them are covered in the book. However, complete information on this subject is contained in the PHP language manual, which can be found on the PHP website. Be careful not to use new features unique to PHP 4.0 if your server is running PHP 3.x.
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.
An assignment to an array element looks the same as an assignment to a variable, except for the square brackets () that are added after the name of the array variable. The index / key of the element is indicated in square brackets. If no index / key is specified, PHP will automatically pick the smallest unoccupied numeric index.
"zero", 1 => "one"); $ my_arr = "two"; $ my_arr = "three"; var_dump ($ my_arr); // assignment without specifying index / key $ my_arr = "four"; $ my_arr = "five"; echo "
"; var_dump ($ my_arr);?>
To change a specific value, you just need to assign a new value to an already 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, incremented by 1. If there are no integer indexes in the array yet, the key will be 0 (zero).
Note that the largest integer key value does not necessarily exist in the array at the moment, this may be due to the removal of array elements. After the elements have been removed, the array is not reindexed. Let's give the following example to make it clearer:
"; print_r ($ my_arr); // Add an item (note that the new key will be 3 instead of 0). $ my_arr = 6; echo"
"; print_r ($ my_arr); // Reindexing: $ my_arr = array_values ($ my_arr); $ my_arr = 7; echo"
"; print_r ($ my_arr);?>
This example uses two new functions, print_r () and array_values (). Array_values () returns an indexed array (re-indexes the returned array with numeric indices), and print_r works like var_dump, but outputs arrays in a more readable way.
We can now consider a third way to create arrays:
The example showed the third way to create an array. If the $ weekdays array has not been created yet, 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, this can lead to unexpected results from the script.
If you have any doubts about whether a variable is an array, use the is_array function. For example, validation can be performed as follows:
"; $ no =" regular string "; echo is_array ($ no)?" Array ":" Not an array ";?>
PHP supports scalar and composite data types. In this article, we will discuss one of the composite types: arrays. An array is a collection of data values, organized as an ordered set of key-value pairs.
This article talks about creating an array, adding items to an array. There are many built-in functions that work with arrays in PHP, because arrays are common and useful to use. For example, if you want to send an email to more than one email address, you can store the email addresses in an array and then loop through the array, sending messages to the email address taken from the array.
Indexed and associative arrays
There are two kinds of arrays in PHP: indexed and associative. Indexed array keys are integers starting at 0. Indexed arrays are used when you need a specific position in an array. Associative arrays behave like two columns of a table. The first column is the key that is used to access the value (second column).
PHP internally stores all arrays as associative arrays, so the only difference between associative and indexed arrays is that the keys appear. Some functions are primarily intended for use with indexed arrays, since they assume that your keys are sequential integers starting at 0. In both cases, the keys are unique - that is, you cannot have two elements with the same key, regardless on whether the key is a string or an integer.
V PHP arrays have an internal ordering of their elements that is independent of keys and values, and there are functions that you can use to traverse arrays based on this internal order.
Defining elements in an array
You can access specific values from an array by using the array name followed by the element key (sometimes called an index) in square brackets:
$ age ["Fred"]; $ shows;
The key can be a string or an integer. String values as numbers (no leading zeros) are treated as integers. Thus, $ array and $ array [‘3’] refer to the same element, but $ array ['03 '] refers to another element. Negative numbers can also be used as keys, but they do not specify positions from the end of the array, as in Perl.
It is not necessary to enclose the key in quotes. For example, $ array [‘Fred’] like $ arrat. Still considered good style PHP always use quotes. If the index is without quotes, then PHP uses the constant value as the index:
Define ("index", 5); echo $ array; // will return $ array, not $ array ["index"];
If you want to substitute a number into the index, then you need to do this:
$ age ["Clone $ number"]; // will return, for example, $ age ["Clone5"];
However, do not include the key in quotes in the following case:
// wrong print "Hello, $ person [" name "]"; print "Hello, $ person [" name "]"; // correct print "Hello, $ person";
Storing data in arrays
When you try to store a value in an array, an array will be automatically created, if it did not exist before, but when you try to retrieve a value from an array that was not defined, the array will not be created. For example:
// $ addresses not defined until now echo $ addresses; // nothing echo $ addresses; // nothing $ addresses = "spam@cyberpromo.net"; echo $ addresses; // print "Array"
You can use simple assignment to initialize an array in a program:
$ addresses = "spam@cyberpromo.net"; $ addresses = "abuse@example.com"; $ addresses = "root@example.com"; // ...
We have declared an index array with integer indices starting at 0.
Associative array:
$ price ["Gasket"] = 15.29; $ price ["Wheel"] = 75.25; $ price ["Tire"] = 50.00; // ...
An easier way to initialize an array is to use the construct Array () which builds an array from its arguments:
$ addresses = array ("spam@cyberpromo.net", "abuse@example.com", "root@example.com");
To create an associative array using Array (), use => character separating indices from values:
$ price = array ("Gasket" => 15.29, "Wheel" => 75.25, "Tire" => 50.00);
Pay attention to the use of spaces and alignment. We could group the code, but this would be less descriptive:
$ price = array ("Gasket" => 15.29, "Wheel" => 75.25, "Tire" => 50.00);
To create an empty array, you need to call the construction Array () no arguments:
$ addresses = Array ();
You can specify a start key in an array and then a list of values. The values are entered into an array, starting with a key and then incrementing:
$ days = array (1 => "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); // 2 is Tuesday, 3 is Wednesday, etc.
If the starting index is a string, then subsequent indexes become integers starting at 0. So the following code is probably an error:
$ whoops = array ("Friday" => "Black", "Brown", "Green"); // same as $ whoops = array ("Friday" => "Black", 0 => "Brown", 1 => "Green");
Adding a new element to the end of the array
To insert multiple values at the end of an existing indexed array, use the syntax:
$ family = array ("Fred", "Wilma"); // $ family = "Fred" $ family = "Pebbles"; // $ family = "Pebbles"
This construct assumes that the array indices are numbers and assigns the next available numeric index to the element, starting at 0. Trying to add an element to an associative array is almost always a programmer mistake, but PHP will add new elements with numeric indices (starting at 0) without issuing a warning:
$ person = array ("name" => "Fred"); // $ person ["name"] = "Fred"; $ person = "Wilma"; // $ person = "Wilma"
At this stage, we will finish the introductory part of working with arrays in PHP. I am waiting for you in the next article.
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 using php, and all of them can be useful for individual cases.
"Operator +"
This is a simple but tricky way:
$ c = $ a + $ b
This adds only those keys 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 $ b array is absent in the $ a array, 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, the sum changes from the change of places of the terms: $ a + $ b! = $ B + $ a - this is worth remembering.
Now for a 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 strings. Great for concatenating two or more numerically indexed arrays:
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 appended to the end of the array.
Array_merge_recursive function
Does the same thing as array_merge but also recursively iterates through each branch of the array and does the same with the descendants.
Array_replace () function
Replaces elements of an array with elements of other passed arrays.
Array_replace_recursive () function
The same as array_replace only processes all the branches of the array.
array_pad
Adds multiple elements to the array.
Syntax:
Array array_pad (array input, int pad_size, mixed pad_value)
Array_pad () 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 equal to 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 the original input array.
An example of using the 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
Applying 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 the specified arrays after being processed by the custom callback function.
The number of parameters passed to the user-defined function must match the number of arrays passed to the array_map () function.
An example of using the array_map () function: Processing one 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
)
An 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 above example will output the following:
// printout of $ cArray (
=> The number 1 in Spanish is uno
=> The number 2 in Spanish is dos
=> Number 3 in Spanish is tres
=> Number 4 in Spanish is cuatro
=> The number 5 in Spanish is cinco
)
// printout of $ dArray (
=> Array
=> uno
)
=> Array
=> dos
)
=> Array
=> tres
)
=> Array
=> cuatro
)
=> Array
=> cinco
)
Typically, the array_map () function is applied to arrays of the same dimension. If the 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.
An 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 above 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 retrieves the last element from the arr array and returns it, removing it after that. With this function, we can build structures that resemble a stack. If the arr array was empty, or if it is not an array, the function returns an empty NULL string.
After using the array_pop () function, the array cursor is set to the beginning.
An example of using the array_pop () function:
$ fruits = array_pop ($ stack);
print_r ($ stack);
print_r ($ fruits);
?>
The example will output the following:
Array (
=> orange
=> banana
=> apple
)
The function is supported by PHP 4, PHP 5
array_push
Adds one or more elements to the end of an array.
Syntax:
Int array_push (array arr, mixed var1 [, mixed var2, ..])
Array_push () adds var1, var2, etc. to arr. She assigns them numerical indices - just as it does for standard ones.
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, but shorter
An example of using the array_push () function:
array_push ($ stack, "apple", "raspberry");
print_r ($ stack);
?>
The example will output the following:
Array (
=> orange
=> banana
=> apple
=> raspberry
)
Note that array_push () takes an array like a stack and always adds elements to the end of it.
The function is supported by PHP 4, PHP 5
array_shift
Retrieves and removes the first element in an array.
Syntax:
Mixed array_shift (array arr)
Array_shift () function retrieves the first element of the arr array and returns it. It closely resembles array_pop (),
but it only receives the initial, not the 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 the remaining elements, since all subsequent elements of the array are shifted one position forward. The string keys of the array are not changed.
If arr is empty or is not an array, the function returns NULL.
After using this function, the array pointer moves to the beginning.
An example of using the array_shift () function:
$ fruit = array_shift ($ stack);
print_r ($ stack);
?>
This example will output the following:
Array (
=> banana
=> apple
=> raspberry
)
and the variable $ fruit will have the value "orange"
The function is supported by PHP 4, PHP 5
array_unshift
Adds one or more values to the beginning of an array.
Syntax:
Int array_unshift (list arr, mixed var1 [, mixed var2, ...])
Array_unshift () adds the passed var values to the beginning of the arr array. The order of the new elements in the array is preserved. All numeric indices of the array will be changed so that it starts at zero. All string indices in 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
)
The function is supported by PHP 4, PHP 5
array_unique
Removes duplicate values in an array.
Syntax:
Array array_unique (array arr)
Array_unique () returns an array of all the unique values in arr, along with their keys, by removing all duplicate values. The first encountered key => value pairs are placed in the resulting array. Indexes are saved.
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
)
An 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])
Array_chunk () function splits the original arr array into several arrays, the length of which is specified by the number size. If the dimension of the original array is not divisible by exactly size parts, then the last array will have a lower dimension.
The array_chunk () function returns a multidimensional array, the indices of which start from 0 to the number of arrays received, and the values are the arrays obtained as a result of splitting.
The optional preserve_keys parameter specifies whether to preserve the keys of the original array or not. If this parameter is false (default value), then the indices of the resulting arrays will be specified as numbers starting from zero. If the parameter is true, then the keys of the original array are preserved.
An example of using the 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 that contains the num-sized values specified in the value parameter, starting at the element specified in the start_index parameter.
An example 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 in the input array, filtered according to the results of the custom callback function.
If the original input array is an associative array, the indices are stored in the resulting array.
An example of using the 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 using the array_filter () function, it cannot be changed: add, remove elements or zero the array, since this can lead to incorrect operation of the function.
Function supported by PHP 4> = 4.0.6, PHP 5