Php deletes duplicate array elements and empty element code

Source: Internet
Author: User
Tags foreach

Php can delete an array by using the following two methods:

1. Traverse the array and determine whether the element value is specified. If so, use unset () to delete it. The sample code is as follows:

The code is as follows: Copy code

// $ Var is the element value to be deleted, and $ array is the target array;
Function array_del ($ var, $ array ){
$ I = 0;
Foreach ($ array as $ val ){
If ($ var = $ val ){
Unset ($ array [$ I]);
Break;
  }
$ I ++;
 }
Return $ array;
}

2. Use the array_flip () function to reverse the key name and value. The sample code is as follows:

The code is as follows: Copy code

<? Php
$ A = array ('php', 'css ', 'Java', 'html', 'jquery ');
$ A = array_flip ($ a); // reverse the key name and value
Unset ($ a ['HTML ']); // deletes a specified value element.
$ A = array_flip ($ a); // reverse the array again to restore the key name and value of the array.
Var_dump ($ );
?>

Delete an empty element from an array

Instance:

The code is as follows: Copy code

<? Php
$ Array = ('a' => "abc", 'B' => "bcd", 'C' => "cde", 'D' => "def ", 'E' => "");
Array_filter ($ array );
Echo "<pre> ";
Print_r ($ array );
?>

Result:

Array (

[A] => abc

[B] => bcd

[C] => cde

[D] => def

   )

Removes empty and repeated elements from the array.

The code is as follows: Copy code

<? Php

$ Array = array ('2', 19,33, 88,2, 99, '', 33 ,'');
Function delArrayRepeat ($ arr ){
If (is_array ($ arr )){
$ Arr = array_unique ($ arr );
Foreach ($ arr as $ k =>$ v ){
If ($ v = ''){
Unset ($ arr [$ k]);
   }
  }
$ Result = $ arr;
} Else {
$ Result = "The parameter must be an array! ";
 }
Return $ result;
}
$ Res = delArrayRepeat ($ array );
Print_r ($ res );

?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.