This is a discussion on Using Arrays in PHP within the PHP Programming forums, part of the Web Development category; Hi All, Can you guys help me to get a logic for the below: Need a program to show the ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Hi All, Can you guys help me to get a logic for the below: Need a program to show the below output as per below requirement? With use of array, display customer Id and Customer name in random order when I refresh the browser. Output should look like below: First Refresh: Ajay 19 10000 Amit 22 20000 Amar 78 30000 Second Refresh: Amar 78 30000 Amit 22 20000 Ajay 19 10000 |
| Sponsored Links |
| |||
| Extracting Multiple Values To copy all of an array's values into variables, use the list( ) construct: list($variable, ...) = $array; The array's values are copied into the listed variables in the array's internal order. By default that's the order in which they were inserted, but the sort functions described later let you change that. Here's an example: $person = array('Fred', 35, 'Betty'); list($name, $age, $wife) = $person; // $name is 'Fred', $age is 35, $wife is 'Betty' If you have more values in the array than in the list( ), the extra values are ignored: $person = array('Fred', 35, 'Betty'); list($name, $age) = $person; // $name is 'Fred', $age is 35 If you have more values in the list( ) than in the array, the extra values are set to NULL: $values = array('hello', 'world'); list($a, $b, $c) = $values; // $a is 'hello', $b is 'world', $c is NULL Two or more consecutive commas in the list( ) skip values in the array: $values = range('a', 'e'); // use range to populate the array list($m,,$n,,$o) = $values; // $m is 'a', $n is 'c', $o is 'e' To extract only a subset of the array, use the array_slice( ) function: $subset = array_slice(array, offset, length); The array_slice( ) function returns a new array consisting of a consecutive series of values from the original array. The offset parameter identifies the initial element to copy (0 represents the first element in the array), and the length parameter identifies the number of values to copy. The new array has consecutive numeric keys starting at 0. For example: $people = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Jo'); $middle = array_slice($people, 2, 2); // $middle is array('Harriet', 'Brenda') It is generally only meaningful to use array_slice( ) on indexed arrays (i.e., those with consecutive integer indices starting at 0):
__________________ Thanks & Regards Sabari... |
| |||
| Converting Between Arrays and Variables PHP provides two functions, extract( ) and compact( ), that convert between arrays and variables. The names of the variables correspond to keys in the array, and the values of the variables become the values in the array. For instance, this array: $person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty'); can be converted to, or built from, these variables: $name = 'Fred'; $age = 35; $wife = 'Betty'; The extract( ) function automatically creates local variables from an array. The indices of the array elements are the variable names: extract($person); // $name, $age, and $wife are now set If a variable created by the extraction has the same name as an existing one, the extracted variable overwrites the existing variable. You can modify extract( )'s behavior by passing a second argument. Appendix A describes the possible values for this second argument. The most useful value is EXTR_PREFIX_ALL, which indicates that the third argument to extract( ) is a prefix for the variable names that are created. This helps ensure that you create unique variable names when you use extract( ). It is good PHP style to always use EXTR_PREFIX_ALL, as shown here: $shape = "round"; $array = array("cover" => "bird", "shape" => "rectangular"); extract($array, EXTR_PREFIX_ALL, "book"); echo "Cover: $book_cover, Book Shape: $book_shape, Shape: $shape"; Cover: bird, Book Shape: rectangular, Shape: round The compact( ) function is the complement of extract( ). Pass it the variable names to compact either as separate parameters or in an array. The compact( ) function creates an associative array whose keys are the variable names and whose values are the variable's values. Any names in the array that do not correspond to actual variables are skipped. Here's an example of
__________________ Thanks & Regards Sabari... |
| |||
| Traversing Arrays The most common task with arrays is to do something with every element—for instance, sending mail to each element of an array of addresses, updating each file in an array of filenames, or adding up each element of an array of prices. There are several ways to traverse arrays in PHP, and the one you choose will depend on your data and the task you're performing. The most common way to loop over elements of an array is to use the foreach construct: $addresses = array('spam@cyberpromo.net', 'abuse@example.com'); foreach ($addresses as $value) { echo "Processing $value\n"; } Processing spam@cyberpromo.net Processing abuse@example.com PHP executes the body of the loop (the echo statement) once for each element of $addresses in turn, with $value set to the current element. Elements are processed by their internal order. An alternative form of foreach gives you access to the current key: $person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma'); foreach ($person as $key => $value) { echo "Fred's $key is $value\n"; } Fred's name is Fred Fred's age is 35 Fred's wife is Wilma In this case, the key for each element is placed in $key and the corresponding value is placed in $value. The foreach construct does not operate on the array itself, but rather on a copy of it. You can insert or delete elements in the body of a foreach loop, safe in the knowledge that the loop won't attempt to process the deleted or inserted elements. Every PHP array keeps track of the current element you're working with; the pointer to the current element is known as the iterator. PHP has functions to set, move, and reset this iterator. The iterator functions are: current( ) Returns the element currently pointed at by the iterator
__________________ Thanks & Regards Sabari... |
| |||
| Acting on Entire Arrays PHP has several useful functions for modifying or applying an operation to all elements of an array. You can merge arrays, find the difference, calculate the total, and more; this can all be accomplished by using built-in functions. The array_sum( ) function adds up the values in an indexed or associative array: array_sum( ) $sum = array_sum(array); For example: $scores = array(98, 76, 56, 80); $total = array_sum($scores); // $total = 310 array_merge( ) The array_merge( ) function intelligently merges two or more arrays: $merged = array_merge(array1, array2 [, array ... ]) If a numeric key from an earlier array is repeated, the value from the later array is assigned a new numeric key: $first = array('hello', 'world'); // 0 => 'hello', 1 => 'world' $second = array('exit', 'here'); // 0 => 'exit', 1 => 'here' $merged = array_merge($first, $second); // $merged = array('hello', 'world', 'exit', 'here') If a string key from an earlier array is repeated, the earlier value is replaced by the later value: $first = array('bill' => 'clinton', 'tony' => 'danza'); $second = array('bill' => 'gates', 'adam' => 'west'); $merged = array_merge($first, $second); // $merged = array('bill' => 'gates', 'tony' => 'danza', 'adam' => 'west') array_diff( ) The array_diff( ) function identifies values from one array that are not present in others: $diff = array_diff(array1, array2 [, array ... ]); For example: $a1 = array('bill', 'claire', 'elle', 'simon', 'judy'); $a2 = array('jack', 'claire', 'toni'); $a3 = array('elle', 'simon', 'garfunkel'); // find values of $a1 not in $a2 or $a3 $diff = array_diff($a1, $a2, $a3); // $diff is array('bill', 'judy'); Values are compared using ===, so 1 and "1" are considered different. The keys of the first array are preserved, so in
__________________ Thanks & Regards Sabari... |
| |||
| Using Arrays Arrays crop up in almost every PHP program. In addition to their obvious use for storing collections of values, they're also used to implement various abstract data types. In this section, we show how to use arrays to implement sets and stacks. Arrays let you implement the basic operations of set theory: union , intersection, and difference. Each set is represented by an array, and various PHP functions implement the set operations. The values in the set are the values in the array—the keys are not used, but they are generally preserved by the operations. The union of two sets is all the elements from both sets, with duplicates removed. The array_merge( ) and array_unique( ) functions let you calculate the union. Here's how to find the union of two arrays: function array_union($a, $b) { $union = array_merge($a, $b); // duplicates may still exist $union = array_unique($union); return $union; } $first = array(1, 'two', 3); $second = array('two', 'three', 'four'); $union = array_union($first, $second); print_r($union); Array ( [0] => 1 [1] => two [2] => 3 [4] => three [5] => four ) The intersection of two sets is the set of elements they have in common. PHP's built-in array_intersect( ) function takes any number of arrays as arguments and returns an array of those values that exist in each. If multiple keys have the same value, the first key with that value is preserved. Another common function to perform on a set of arrays is to get the difference; that is, the values in one array that are not present in another array. The array_diff( ) function calculates this, returning an array with values from the first array that are not present in the second. The following code takes the difference of two arrays: $first = array(1, 'two', 3); $second = array('two', 'three', 'four'); $difference = array_diff($first, $second); print_r($difference); Array ( [0] => 1 [2] => 3 )
__________________ Thanks & Regards Sabari... |
| |||
| hello, Mr.Venkat Charya.. Here i have given simple array function for your query... i hope its match to your requirement.... First Refresh: Ajay 19 10000 Amit 22 20000 Amar 78 30000 Second Refresh: Amar 78 30000 Amit 22 20000 Ajay 19 10000 ----- $vGetNewArray = array(array("AJAY", 19, 10000), array("AMIT", 22, 20000), array("AMAR", 24, 30000)); print_r($vGetNewArray[array_rand($vGetNewArray)]); Result: first Refresh: Array ( [0] => AMIT [1] => 22 [2] => 20000 ) Second Refresh: Array ( [0] => AJAY [1] => 19 [2] => 10000 ) |
| |||
| Hi Raj, Thanks for your reply. You close to my need but my need is little bit different here. As you mention array $vGetNewArray = array(array("AJAY", 19, 10000), array("AMIT", 22, 20000), array("AMAR", 24, 30000)); It is right but in display you showing one item randomly in one refresh. Actually i want to show all three item but changing the display order in every time while i refresh the browser. First Refresh it will list all three like that Ajay 19 10000 Amit 22 20000 Amar 78 30000 In Second Refresh it will list all three but different order like that Amar 78 30000 Amit 22 20000 Ajay 19 10000 Something like that. Can you tell me how i can get this result ![]() Thanks in advance |
| |||
| Hi Venkat Charya.. see this code.. i hope, its suitable to your requirement.. $vGetNewArray = array(array("AJAY", 19, 10000), array("AMIT", 22, 20000), array("AMAR", 24, 30000)); $aRendomKeys = array_rand(array_keys($vGetNewArray), count($vGetNewArray)); function funGetArray($pmArrayValue) { global $vGetNewArray; return $vGetNewArray[$pmArrayValue]; } $aFinalResult = array_map("funGetArray", $aRendomKeys); print_r($aFinalResult); Result: Array ( [0] => Array ( [0] => AMAR [1] => 24 [2] => 30000 ) [1] => Array ( [0] => AMIT [1] => 22 [2] => 20000 ) [2] => Array ( [0] => AJAY [1] => 19 [2] => 10000 ) ) |
| |||
| hi, Here we see use of strnatcmp() function. strnatcmp -- String comparisons using a "natural order" algorithm. this function sorting the array using comparison algorithm that orders alphanumeric strings. this called as a "natural ordering". For example: $arr = array("img12.png", "img10.png", "img2.png", "img1.png"); usort($arr, "strnatcmp"); print_r($arr); //output Array ( [0] => img1.png [1] => img2.png [2] => img10.png [3] => img12.png ) --kamal. |
| |||
| hi, Here we see use of strcmp() function. strcmp -- Binary safe string comparison Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. For example: $arr = array("img12.png", "img10.png", "img2.png", "img1.png"); usort($arr, "strcmp"); print_r($arr); //output Array ( [0] => img1.png [1] => img10.png [2] => img12.png [3] => img2.png ) --kamal. |
| |||
| Hi all, Can anybody tell me how we concatenate any string in already built one array? Eg. $vArr = array("Test1","Test2","Test3","Test4","Test5"); Want to add "*" sign before array values so output should come like that. *Test1 *Test2 *Test3 *Test4 *Test5 Thanks in advance. |
| |||
| Hi Venkat Charya... you can use array_map function for your need... <? $vArr = array("Test1","Test2","Test3","Test4","Test5"); $aFinalResult = array_map("funAddStr", $vArr); print_r($aFinalResult); function funAddStr($pmArrayValue) { return "*".$pmArrayValue; } ?> Result: Array ( [0] => *Test1 [1] => *Test2 [2] => *Test3 [3] => *Test4 [4] => *Test5 ) |
| |||
| Hi, I want to search one string from the array values For example i have an array with {a,test,images/test,testing} search key is images i want to get new array as {images/test} if i search with test new array is {test,images/test,testing} Can anyone help for this?
__________________ With, J. Jeyaseelan Everything Possible |
| |||
| Array Swap hi Jeyaseelansarc, just now i try to get swap array values with in a array, this will help little bit idea to swap between one array to another, i'll try to give that code ASAP. $a=array('one','two','three','four'); $b=array_swap($a,1,3); print_r($b); // Swap 2 elements in array preserving keys. function array_swap(&$array,$key1,$key2) { $v1=$array[$key1]; $v2=$array[$key2]; $out=array(); foreach($array as $i=>$v) { if($i===$key1) { $i=$key2; $v=$v2; } else if($i===$key2) { $i=$key1; $v=$v1; } $out[$i]=$v; } return $out; } Out put: Array ( [0] => one [3] => four [2] => three [1] => two )
__________________ Thanks & Regards Sabari... |
| |||
| converting a PHP array into a string This simple function converts a PHP array to a string containing a PHP array declaration. It can be used to put an array into a database field. It can then be retrieved and eval()'d in another script. <?php $arr = array('W','E','L','C','O','M','E'); $string = implode($arr, ''); echo $string; ?> Output: WELCOME
__________________ Thanks & Regards Sabari... |
| |||
| Cleans Array of Empty Records Here is the function that cleans array of empty records. It goes recursive through multidimensional array and erases any item that has empty value or is empty array. This actually works on any variable type, not just arrays. function clean_item ($p_value) { if (is_array ($p_value)) { if ( count ($p_value) == 0) { $p_value = null; } else { foreach ($p_value as $m_key => $m_value) { $p_value[$m_key] = clean_item ($m_value); if (empty ($p_value[$m_key])) unset ($p_value[$m_key]); } } } else { if (empty ($p_value)) { $p_value = null; } } return $p_value; } $m_array['aaa'] = 'bbb'; $m_array['ccc'] = ''; $m_array['ddd'] = Array(); $m_array['eee']['fff'] = Array(); $m_array['eee']['ggg'] = ''; $m_array['eee']['hhh'] = 'iii'; $m_array['eee']['j']['a'] = 'gh'; $m_array['eee']['j']['b'] = ''; $m_array['eee']['j']['c'] = 'rty'; $m_array['eee']['j']['d'] = Array(); $m_array['eee']['j']['e'][1] = 'r'; $m_array['eee']['j']['e'][2] = 'y'; $m_array['eee']['j']['e'][1] = ''; $m_array['eee']['j']['e'][4] = Array(); $m_array['eee']['j']['e'][5] = ''; $m_clean = clean_item ($m_array); print_r ($m_array); echo "<br>"; print_r ($m_clean); OutPut: Variable $m_clean contains: Array ( [aaa] => bbb [eee] => Array ( [hhh] => iii [j] => Array ( [a] => gh [c] => rty [e] => Array ( [2] => y ) ) ) )
__________________ Thanks & Regards Sabari... |
| |||
| convert a php array into a javascript array $a=array('one','two','three','four'); $vResult = arrayToJS4($a,"ArrayVal"); echo $vResult; //make javascript ready function output($string) { $string = str_replace( array( '\\' , '\'' ), array('\\\\', '\\\'') , $string); //-> for javascript array $string = str_replace( array("\r\n", "\r", "\n") , '<br>' , $string); //nl2br return $string; } function arrayToJS4($array, $baseName ) { //Write out the initial array definition $output = $baseName . " = new Array(); \r\n "; //Reset the array loop pointer reset ($array); //Use list() and each() to loop over each key/value //pair of the array while (list($key, $value) = each($array)) { if (is_numeric($key)) { //A numeric key, so output as usual $outKey = "[" . $key . "]"; } else { //A string key, so output as a string $outKey = "['" . $key . "']"; } if (is_array($value)) { //The value is another array, so simply call //another instance of this function to handle it $output .= arrayToJS4($value, $baseName . $outKey); } else { //Output the key declaration $output .= $baseName . $outKey . " = "; //Now output the value if (is_string($value)) { //Output as a string, as we did before $output .= "'" . output($value) . "'; \r\n "; } else if ($value === false) { //Explicitly output false $output .= "false; \r\n"; } else if ($value === NULL) { //Explicitly output null $output .= "null; \r\n"; } else if ($value === true) { //Explicitly output true $output .= "true; \r\n"; } else { //Output the value directly otherwise $output .= $value . "; \r\n"; } } } return $output; } OutPut: ArrayVal = new Array(); ArrayVal[0] = 'one'; ArrayVal[1] = 'two'; ArrayVal[2] = 'three'; ArrayVal[3] = 'four';
__________________ Thanks & Regards Sabari... |