RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (6.59%*) • Fixed: 5.39% (6.59%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.48%*) • Investment PI: 5.39% (6.59%*)

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

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 complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment