Jump to content


Photo

Remove Empty Array Elements


  • Please log in to reply
2 replies to this topic

#1 jream

jream

    Administrator

  • Administrators
  • 52 posts

Posted 09 December 2012 - 09:26 PM

This is the fastest way I've seen to remove empty array elements without having to do your own loop.

<?php

$data = array(
  'name' => "Ted',
  'age' => 20,
  'extra' => ''
);

array_filter('strlen', $data);

 

Remember, array format changes the reference of the array passed on, so you do not need to re-assign $data.

 

* Fixed thanks MikeXS



#2 MikeXS

MikeXS

    Newbie

  • Members
  • Pip
  • 2 posts

Posted 10 December 2012 - 08:46 AM

Hey Jesse, did you mean to use array_filter there instead of array_format ? Unless array_format is a custom function ?

Here's an example with array filter:
 
$data = array(
'name' => 'Ted',
'age' => 20,
'extra' => ''
);

var_dump($data);
Output:
array
  'name' => string 'Ted' (length=3)
  'age' => int 20
  'extra' => string '' (length=0)

Array_Filter
 
$data = array_filter($data,'strlen');

var_dump($data);
Output:
array
'name' => string 'Ted' (length=3)
'age' => int 20
 
Or even just straight up like :
$data = array_filter($data);

var_dump($data);
Output:
array
  'name' => string 'Ted' (length=3)
  'age' => int 20


#3 jream

jream

    Administrator

  • Administrators
  • 52 posts

Posted 11 December 2012 - 01:17 AM

Yes you are right, fixed!






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users