1

I have a 2-dimensional PHP array containing strings ($fulltable) which I'm trying to fit into the datables grid (https://www.datatables.net/).

Sometimes some of the strings are really long. I'd like to truncate each string to lets say to 75 charachters, which will make the fields more manageable on display.

Is there an easy PHP function to do this or should I just create a double loop like this?

foreach ($fulltable as $row) {
    foreach ($row as $field) {
        // TRUNCATE FIELD HERE
    }  
}

3 Answers 3

3

You could use array_walk_recursive() to do this and take the value by reference, e.g.

array_walk_recursive($arr, function(&$v){
    $v = substr($v, 0, 75);
});
Sign up to request clarification or add additional context in comments.

Comments

1

Use mb_substr:

mb_substr($field, 0, 30);

Where 0 is the beginning and 30 is the end, 30 could be anything you want, the length of your output.

Comments

1

array_map() or array_walk() will apply a function to the contents of an array (single dimension), and be probably faster that looping with foreach.

There is also array_walk_recursive() for multi dimensional arrays.

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.