0

I have a PHP/JSON as show below.

JSON:

{"posts_id_en":"101, 102, 103","posts_id_fr":"", "reports_id_en":"101, 102", "reports_id_fr":"101"}

PHP code:

echo count(explode(",", $data->posts_id_en));    //  Line A  (3)

echo count(explode(",", $data->posts_id_fr));    // Line B   (1)

echo count(explode(",", $data->reports_id_en));    // Line C  (2)

echo count(explode(",", $data->reports_id_fr));    // Line D  (1)

Line A php code, Line C php code and Line D php code print 3, 2, and 1.

Problem Statement:

I am wondering what changes I need to make in the php code above at Line B so that it prints 0 as there are no elements inside posts_id_fr

user1950349
  • 4,738
  • 19
  • 67
  • 119

4 Answers4

0

You just need to make sure there is no empty values inside that array. Because when empty string is exploded it will create one element with value as blank.

Remove those values using array_filter

echo count(array_filter(explode(",", $data->posts_id_fr)));

// Will print 0

Just in case if you want to loop through as suggested by GrumpyCrouton

foreach($data as $key => $value)
{
  echo $key . ' : ' . count(array_filter(explode(",", $value))) . PHP_EOL;
}

Output:
posts_id_en : 3
posts_id_fr : 0 
reports_id_en: 2
reports_id_fr: 1
Dark Knight
  • 6,116
  • 1
  • 15
  • 37
0

You must check if the value is set before trying to use the value

$str = '{"posts_id_en":"101, 102, 103","posts_id_fr":"", "reports_id_en":"101, 102", "reports_id_fr":"101"}';

$obj = json_decode($str);

foreach ( $obj as $o=>$v) {
    echo $o . ' ';
    echo strlen($v) > 0 ? count(explode(",", $v)) : 0 ;
    echo PHP_EOL;
}

Results

posts_id_en 3
posts_id_fr 0
reports_id_en 2
reports_id_fr 1
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

Slight variation here, you can use preg_split and use a flag to ignore empty splits. Here we are splitting on non-digits.

<?php

$str = '{"posts_id_en":"101, 102, 103","posts_id_fr":"", "reports_id_en":"101, 102", "reports_id_fr":"101"}';
$arr = json_decode($str, true);

$arr = array_map(function($item) {
    $nums = preg_split('/[^0-9]/', $item, -1, PREG_SPLIT_NO_EMPTY);

    return $nums;
}, $arr);

var_export($arr);

$arr = array_map('count', $arr);

var_export($arr);

Output:

array (
  'posts_id_en' => 
  array (
    0 => '101',
    1 => '102',
    2 => '103',
  ),
  'posts_id_fr' => 
  array (
  ),
  'reports_id_en' => 
  array (
    0 => '101',
    1 => '102',
  ),
  'reports_id_fr' => 
  array (
    0 => '101',
  ),
)array (
  'posts_id_en' => 3,
  'posts_id_fr' => 0,
  'reports_id_en' => 2,
  'reports_id_fr' => 1,
)

The intermediate step is included so you can see the result of the preg_split.

Progrock
  • 7,373
  • 1
  • 19
  • 25
0
echo count(preg_split("/,/", $data->posts_id_fr,-1, PREG_SPLIT_NO_EMPTY)); 

enter image description here

Pablo Escobar
  • 393
  • 2
  • 16