Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Truncate an Array from the “Left” or “Right” with PHP

In an upcoming article on importing Imgur images into WordPress, we use a function that will truncate data either side of the returned array to remove either the first or last image (Imgur people have a bad habit of throwing in a "cat tax"). Those leading and trailing images often aren't relevant if you want to display the data yourself, so we wrote the following function to remove them (in our upcoming shortcode, the attribute of remove="1,2" would remove the first image and the last two pictures).

Incidentally, when dealing with a returned array of images, you'll often want to remove other images (not just the first and last) and you will normally want to reference them by the order in which they're displayed on a screen. Since an array index starts at 0 and not 1, there's another relevant function we'll share shortly that'll re-index an array to start at 1 (meaning you can remove images by their order on a screen, not the resulting array). When published, you'll find that function here.

The Result

Consider the following array:

1
$arr = array('0' => 'a', '1' => 'b', '2' => 'c', '3' => 'd', '4' => 'e');

We can remove the first element and the last two by using the following:

1
<?php 
2
$newarray = beliefmedia_truncate_array($arr, $left = &quot;1&quot;, $right = &quot;2&quot;);
3
print_r($newarray);

The result:

1
Array
2
(
3
    [0] => a
4
    [1] => b
5
)

The PHP Function

1
<?php 
2
/*
3
 Truncate an Array from the &quot;Left&quot; or &quot;Right&quot; with PHP
4
 http://www.beliefmedia.com/truncate-an-array-php
5
*/
6
 
7
function beliefmedia_truncate_array(array $array, $left, $right) {
8
  $left = $left - 1; if (empty($right)) $right = count($array);
9
  $array = array_slice($array, $left, $right - $left, true);
10
 return (array) $array;
11
}
12
?>

Download


Title: Truncate an Array from the "Left" or "Right" with PHP
Description: Truncates an Array from the "Left" or "Right" with PHP.
  Download • Version 0.2, 497.0B, zip, Category: PHP Code & Snippets

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Connecticut)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

READY TO HAVE A CHAT? CALL US ANYTIME ON 1300 235 433