user1213167
user1213167

Reputation:

PHP Remove last word from an array

I've mysql query in array in the below format,i've to remove the last and

Array ( [0] => date = '2012-02-22' and time ='08:49' and  [1] => date = '2012-02-22' and time ='08:49' and )

I get this array as out put after putting into this function array_values();

I tried rtim and trim.

Thanks in-advance

Upvotes: 1

Views: 631

Answers (4)

inquam
inquam

Reputation: 12932

Try the following,

array_push(yourarray, rtrim(array_pop(yourarray), ' and'));

It will pop the last element, trim away the " and" at the end and then re-add the modified element to the array.

For example,

$yourarray = array("date = '2012-02-22' and time ='08:49' and",  
             "date = '2012-02-22' and time ='08:49' and ");

var_dump($yourarray);
array_push($yourarray, rtrim(array_pop($yourarray), ' and'));
var_dump($yourarray);

outputs the following

array(2) {
  [0]=>
  string(41) "date = '2012-02-22' and time ='08:49' and"
  [1]=>
  string(42) "date = '2012-02-22' and time ='08:49' and "
}

array(2) {
  [0]=>
  string(41) "date = '2012-02-22' and time ='08:49' and"
  [1]=>
  string(37) "date = '2012-02-22' and time ='08:49'"
}

So, the last " and" in the last element has been removed.

Upvotes: 2

Mouna Cheikhna
Mouna Cheikhna

Reputation: 39638

use trim() with an optional parameter 'and'

foreach($myarray as $element)
{
  trim($element, 'and')
}

EDIT : to remove only last "and" in the last element

 trim($myarray[count($myarray) -1] , 'and')

Upvotes: 0

Cheery
Cheery

Reputation: 16214

$arr = array_map("remove_last_and", $arr);
function remove_last_and($el) {
    return preg_replace('/\s*and\s*$/i', '', $el);
}

Example:

$arr = array("date = '2012-02-22' and time ='08:49' and",  
             "date = '2012-02-22' and time ='08:49' and ");
$arr = array_map("remove_last_and", $arr);
function remove_last_and($el) {
    return preg_replace('/\s*and\s*$/i', '', $el);
}
var_dump($arr);

Output:

array(2) {
  [0]=>
  string(37) "date = '2012-02-22' and time ='08:49'"
  [1]=>
  string(37) "date = '2012-02-22' and time ='08:49'"
}

ps: I did not write the inline or anonymous function as I do not know what version of PHP you are using. But, as example, you can write as of php 5.3

$arr = array_map(function($el) {
            return preg_replace('/\s*and\s*$/i', '', $el);
       }, $arr);

ps: I do not think that use of trim or rtrim is good as it could remove the part of the query if the query is slightly different and has 'and' letters close to the end of the string.

Upvotes: 0

Mohora Bogdan
Mohora Bogdan

Reputation: 71

$a = array ( 0 => "date = '2012-02-22' and time ='08:49' **and**",  1 => "date = '2012-02-22' and time ='08:49' **and**");

function func($v){
    return rtrim($v,' **and**');
}
$b = array_map('func',$a);

Upvotes: 0

Related Questions