Consider the following PHP code that merges two arrays. What will be the output?
<?php $array1 = ["a" => "apple", "b" => "banana"]; $array2 = ["a" => "apricot", "c" => "cherry"]; $result = array_merge($array1, $array2); print_r($result); ?>
Remember that array_merge overwrites values with the same string keys from later arrays.
When merging arrays with string keys, array_merge overwrites the value of keys from the first array with values from the second array if keys are the same. Here, key "a" is overwritten by "apricot".
Given two arrays, what will be the result of array_combine?
<?php $keys = ["x", "y", "z"]; $values = [10, 20, 30]; $result = array_combine($keys, $values); print_r($result); ?>
array_combine uses the first array as keys and the second as values.
The function array_combine creates an array by using the first array as keys and the second array as values. So keys "x", "y", "z" map to 10, 20, 30 respectively.
Look at this PHP code snippet. What error will it produce when run?
<?php $keys = ["a", "b"]; $values = [1, 2, 3]; $result = array_combine($keys, $values); print_r($result); ?>
Check if both arrays have the same number of elements.
array_combine requires both arrays to have the same number of elements. Here, keys has 2 elements but values has 3, so it triggers a warning.
What will this PHP code output?
<?php $array1 = [1, 2, 3]; $array2 = [4, 5]; $result = array_merge($array1, $array2); print_r($result); ?>
For numeric keys, array_merge appends values and reindexes keys.
When merging arrays with numeric keys, array_merge appends the second array's values to the first and reindexes keys starting from 0.
Given these two arrays, how many items will the resulting array have after merging with array_merge?
<?php $array1 = ["x" => 1, "y" => 2, 3]; $array2 = ["y" => 4, 5, 6]; $result = array_merge($array1, $array2); ?>
Remember how array_merge handles string keys and numeric keys differently.
String keys from the second array overwrite those from the first. Numeric keys are appended and reindexed. Here, key "y" is overwritten, and numeric values are appended. The final array has 5 items.