- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Removing empty array elements in PHP
To remove empty array elements in PHP, the code is as follows −
Example
<?php $my_array = array("This", 91, '', null, 102, "is", false, "a", "sample", null); foreach($my_array as $key => $val) if(empty($val)) unset($my_array[$key]); echo "After removing null values from the array, the array has the below elements -"; foreach($my_array as $key => $val) echo ($my_array[$key] ."<br>"); ?>
Output
After removing null values from the array, the array has the below elements -This 91 102 is a sample
An array is defined, that contains strings, numbers and ‘null’ values. The ‘foreach’ loop is used to iterate over the elements and if a value is empty, i.e. it contains null, then it is deleted from the array. The relevant array is displayed again that wouldn’t contain null values.
Advertisements