Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - PHP Built-in Functions for Arrays

By: FYICenter.com

Part:   1  2  3   4  5  6  7 

(Continued from previous part...)

How To Join a List of Keys with a List of Values into an Array?

If you have a list keys and a list of values stored separately in two arrays, you can join them into a single array using the array_combine() function. It will make the values of the first array to be the keys of the resulting array, and the values of the second array to be the values of the resulting array. Here is a PHP script on how to use array_combine():

<?php
$old = array();
$old["Zero"] = "PHP";
$old[1] = "Perl";
$old["Two"] = "Java";
$old["3"] = "C+";
$old[""] = "Basic";
$old[] = "Pascal";
$old[] = "FORTRAN";
$keys = array_keys($old);
$values = array_values($old);
print("Combined:\n");
$new = array_combine($keys, $values);
print_r($new);
print("\n");

print("Combined backward:\n");
$new = array_combine($values, $keys);
print_r($new);
print("\n");
?>

This script will print:

Combined:
Array
(
    [Zero] => PHP
    [1] => Perl
    [Two] => Java
    [3] => C+
    [] => Basic
    [4] => Pascal
    [5] => FORTRAN
)
Combined backward:
Array
(
    [PHP] => Zero
    [Perl] => 1
    [Java] => Two
    [C+] => 3
    [Basic] =>
    [Pascal] => 4
    [FORTRAN] => 5
)

How To Merge Values of Two Arrays into a Single Array?

You can use the array_merge() function to merge two arrays into a single array. array_merge() appends all pairs of keys and values of the second array to the end of the first array. Here is a PHP script on how to use array_merge():

<?php
$lang = array("Perl", "PHP", "Java",);
$os = array("i"=>"Windows", "ii"=>"Unix", "iii"=>"Mac");
$mixed = array_merge($lang, $os);
print("Merged:\n");
print_r($mixed);
?>

This script will print:

Merged:
Array
(
    [0] => Perl
    [1] => PHP
    [2] => Java
    [i] => Windows
    [ii] => Unix
    [iii] => Mac
)

(Continued on next part...)

Part:   1  2  3   4  5  6  7 


Selected Developer Jobs:

More...