Remove empty positions from an array

Asked

Viewed 5,339 times

7

I’m passing a array via GET for PHP and then send it to the client side (Javascript). When I receive it it looks like this:

m_prod = [5,,,,,,,,6,,,,,,];

In other words, it is including a space in the positions that does not contain a value! How can I remove these spaces in Javascript?

<?php
    $m_prod = trim($_GET['m_prod']);
    print("<SCRIPT language=javascript> m_prod = \"$m_prod\"; </SCRIPT>");
?>
  • Just want to remove spaces? Or also reduce the array size?

  • Well, at first I would like to remove the spaces, because then the array would be only with m_prod = [5,6];

  • Then I guess you already have the answer down

  • @Alexandre can explain better where this array comes from? comes from PHP?

  • Yes the array comes from PHP!

  • 1

    @Alexandre then the interesting is to see your PHP code to solve the problem at source. You have access to PHP?

  • 1

    @Sergio already modify the code to show how enough my php!

Show 2 more comments

2 answers

13


You can use the function filter, as follows:

var m_prod = [5, , , , , , , , , ,6 , , , ];

var resultado = m_prod.filter(function(ele){
  return ele !== undefined;
});

console.log(resultado);  // [5,6]
  • 1

    Just what I needed! Thanks @Brunocalza

  • So @Brunocalza, it goes through the filter but still keeps the positions empty! It’s like it doesn’t just return the values!

  • sorry @Alexandre, I don’t understand. keep in mind that m_prod will not be changed.

  • My mistake, instead of using undefined use the "" so returns the fields I need!

8

If the problem comes from PHP I think it should solve in PHP.

To filter an array of empty elements:

$m_prod = array_filter($m_prod);

In case there are numbers inside the array then we have to be extra careful because the 0 validates as false and is removed from the array. So you can do:

$m_prod = array_filter($m_prod, function($value) {
  return !empty($value) || $value === 0;
});

To pass this to Javascript you can render like this:

echo '<script>';
echo 'm_prod = '.json_encode($m_prod);
echo '</script>';
  • 1

    That way is also quiet! Thanks @Sergio

  • 3

    @Alexandre, If you need to create an API in the future, you will always have to sanitize the results. Use PHP to pass on the correct information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.