PHP array of commonly used development functions

  • 2020-05-19 04:21:14
  • OfStack

1. Array processing function:
Tipsy feeling: array processing function is very common in the PHP development, study well array processing function is very important. The array processing function involved in practice: to create an array, a string in the array of mutual transformation, array XML, turn JSON array. The array detection. Merge in the segmentation of the array. The number of the array. Retrieve all values in the array, access to all the key value in the array (subscript)
1. Create an array:
$new = array();
2. implode(delimited,str) concatenates the array value data by the specified characters
 
$arr = array('Hello','World!','Beautiful','Day!'); 
echo implode(" ",$arr); The output  
Hello World! Beautiful Day! 

3.count(arr) calculates the number of cells in an array or the number of attributes in an object
4.is_array(arr) checks whether the variable is an array
5. The array_rand() function randomly selects one or more elements from the array and returns them.
 
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); 
print_r(array_rand($a,1)); 

Output: b
 
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); 
print_r(array_rand($a,2));View Code 
Array ( [0] => c [1] => b ) 

The 6.array_sum() function returns the sum of all the values in the array.
 
$a=array(0=>"5",1=>"15",2=>"25"); 
echo array_sum($a); 

Output: 45
7. The array_slice() function fetches 1 value from the array based on the condition and returns it.
 
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); 
print_r(array_slice($a,1,2));View Code 
Array ( [0] => Cat [1] => Horse ) 

8. The array_count_values() function counts the number of times all the values in the array appear.
 
$a=array("Cat","Dog","Horse","Dog"); 
print_r(array_count_values($a)); The output : 
Array ( [Cat] => 1 [Dog] => 2 [Horse] => 1 ) 

3. Array to XML
 
function array2xml($array, $tag) { 
function ia2xml($array) { 
$xml=""; 
foreach ($array as $key=>$value) { 
if (is_array($value)) { 
$xml.="<$key>".ia2xml($value)."</$key>"; 
} else { 
$xml.="<$key>".$value."</$key>"; 
} 
} 
return $xml; 
} 
return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>"); 
} 
$test['type']='lunch'; 
$test['time']='12:30'; 
$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak'); 
echo array2xml($test,"meal")->asXML(); 

Output:
 
<?xml version="1.0"?> 
<meal> 
<type>lunch</type> 
<time>12:30</time> 
<menu> 
<entree>salad</entree> 
<maincourse>steak</maincourse> 
</menu> 
</meal> 

Related articles: