Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts

In array

0 comments Posted by Unknown at 17:37
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
)
Read More »

Advanced Arrays and Pointers

0 comments Posted by Unknown at 15:51
Advanced C Arrays


In C, an array is formed by laying out all the elements contiguously in memory. The square bracket syntax can be used to refer to the elements in the array. The array as a whole is referred to by the address of the first element which is also known as the "base address" of the whole array.
{
int array[6];
int sum = 0;
sum += array[0] + array[1]; // refer to elements using []
}
0 1 2 3 4 5
array
Index
array[0] array[1] array[2] ...
The array name acts like a pointer to the first element- in this case an (int*). The programmer can refer to elements in the array with the simple [ ] syntax such as array. This scheme works by combining the base address of the whole array with the index to compute the base address of the desired element in the array. It just requires a little arithmetic. Each element takes up a fixed number of bytes which is known at compile-time. So the address of element n in the array using 0 based indexing will be at an offset of (n * element_size) bytes from the base address of the whole array. address of nth element = address_of_0th_element + (n * element_size_in_bytes)

Read More »
 

© 2011. All Rights Reserved | Interview Questions | Template by Blogger Widgets

Home | About | Top