1

I want to limit every array to strings with 15 characters or less. I have tried this code, but it does not work:

$a = [
        "name1" => ['Dewa','Aditya','Pratama'],
        "name2" => ['Brian','Dzikri','Ramadhan'],
];

$result_shortdes = "";
foreach ($a as $values) {
    foreach ($values as $value) {
        if(strlen($result_shortdes) + strlen($value) <= 15)
        {
            $result_shortdes .= "$value,";
        }
    }
}

echo '<pre>';
print_r($result_shortdes);
echo '<pre>';

My expected output is like this:

1. Dewa,Aditya,
2. Brian,
2
  • What is your expected output? Commented Feb 5, 2019 at 4:24
  • this is simple array limit <?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,2)); ?> what you want Commented Feb 5, 2019 at 4:26

2 Answers 2

2

Every time you go to the next name, you need to reset result_shortdes to count the name length again, place the variable inside the first loop like this:

foreach ($a as $values) {
    $result_shortdes = "";
    foreach ($values as $value) {
        if(strlen($result_shortdes) + strlen($value) <= 15)
        {
            $result_shortdes .= "$value,";
        }
    }
    echo '<pre>';
    print_r($result_shortdes);
    echo '<pre>';
}
Sign up to request clarification or add additional context in comments.

Comments

0

you can use $result_shortdes for length and $result to store result like below

$a = [
                "name1" => ['Dewa','Aditya','Pratama'],
                "name2" => ['Brian','Dzikri','Ramadhan'],
        ];

        $result_shortdes = "";
        $result = [];
        foreach ($a as $values) {
            $result_shortdes = "";
            foreach ($values as $value) {
                if(strlen($result_shortdes) + strlen($value) <= 15)
                {
                    $result_shortdes .= "$value,";
                }else{
                   $result[] = $result_shortdes;
                   break;
               }
            }
        }

        echo '<pre>';
        print_r($result);
        echo '<pre>';

Comments

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.