0

I have a set of numbers in a table field in database, the numbers are separated by comma '|1||10||12|'. I am trying to do the following:

$array =  explode('|', $set_of_numbers);

answer

["","1","","10","","12",""]

I need so

["1","10","12"]

as can be done thank you for previously

2
  • 1
    array_filter Commented Aug 24, 2018 at 10:18
  • 2
    "the numbers are separated by comma '|1||10||12|'" Looks like they're not Commented Aug 24, 2018 at 10:23

5 Answers 5

1

Use this, array_filter() function will removes your empty/blank values from array & will return array which has values only.

$set_of_numbers = '|1||10||12|';
$array =  array_filter(explode('|', $set_of_numbers));
Sign up to request clarification or add additional context in comments.

Comments

1

Can you try this,

$set_of_numbers = '|1||10||12|';
$array = array_filter(explode("|", $set_of_numbers), function($value) { return $value!== ''; });

It will work you can use this, I tested this on phpfiddle.

1 Comment

You can simplify that filter to array_filter(..., 'strlen').
0

Try this. This will work.

$set_of_numbers = '|1||10||12|';
$array =  explode('|', $set_of_numbers);
$array = array_filter($array);

Comments

0

You can also use regular expression:

<?php

$a = '|1||10||12|';
$matches = [];
preg_match_all('/(\d+)/', $a, $matches);
var_dump($matches[1]);

http://php.net/manual/en/function.preg-match-all.php

Comments

-1

Try this

$array = trim($array, '|');
$array = explode('||', $set_of_numbers);

5 Comments

That works very specifically for this example, but I'm not sure the spec is that there will always be || in the middle and | and the ends…
Sure, this is a specific answer. But judging by the question, that's what he will always have in his $set_of_numbers.
@deceze Wouldn't that also be true for all the other answers?
@kerbholz No, array_filter works regardless of how many | there are or in what combination.
@deceze Oh, ok, I see, I thought you were talking about the seperator being , or something. Nevermind ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.