2

My php output is an array. Like:

$array = array('banana', 'mango', 'apple');

Now If output is only 'Banana' then it will show simply

Banana

If output is 'banana' & 'mango' or 'apple' the i want to show like

Banana or Mango

If output is all.. then result will be shown

Banana, Mango or Apple

Now I can show result with comma using this code

echo implode(",<br/>", $array);

But How to add or ??

Please help.

I Am Stack
  • 231
  • 3
  • 18
  • 5
    The same answer for [another post](http://stackoverflow.com/questions/8586141/implode-array-with-and-add-and-before-last-item) can be applied to this answer. Almost, a duplicate.. just **and** instead of **or**. – SergeantHacker Feb 17 '16 at 07:11
  • This is the easiest way to do this: $str = implode(', ', array('banana', 'mango', 'apple')); echo substr_replace($str, array(' or'), strrpos($str, ','), 1); – Amit Rajput Feb 17 '16 at 08:04
  • Thanks for your comnments @Amit Rajput .. is that work for 3 or more array list? – I Am Stack Feb 17 '16 at 10:00

5 Answers5

2

Try this:

<?php 
$array = array('banana','mango','apple');
$result = '';
$maxelt = count($array) - 1;
foreach($array as $n => $item) {
    $result .= (                           // Delimiter
        ($n < 1) ? '' :                    //    1st?
        (($n >= $maxelt) ? ' or ' : ', ')  //    last or otherwise?
        ) . $item;                         // Item
}
echo $result;
hherger
  • 1,660
  • 1
  • 10
  • 13
0

use the count and map with that like

$count = count($your_array);
if($count > 3){
    end($array);         // move the internal pointer to the end of the array
    $key = key($array); // fetches the key of the element pointed to by the internal pointer

    $last = $your_array[$key];

    unset($your_array[$key]);
    echo implode(",<br/>", $your_array)."or"$last;
}
0

you can replace last occurrence of a string in php by this function:

function str_lreplace($search, $replace, $subject)
{
    $pos = strrpos($subject, $search);

    if($pos !== false)
    {
        $subject = substr_replace($subject, $replace, $pos, strlen($search));
    }

    return $subject;
}

$array = array('banana', 'mango', 'apple');

$output = implode(", ", $array);

echo $output = str_lreplace(',',' or',$output);
Gouda Elalfy
  • 6,888
  • 1
  • 26
  • 38
0
$count = count($array);

if( $count == 1 ) {

   echo $array[0];

} else if ( $count == 2 ) {

   echo implode(' or ', $array);

} else if ( $count > 2 ) {

   $last_value = array_pop( $array );
   echo implode(', ', $array).' or '.$last_value;

}
linktoahref
  • 7,812
  • 3
  • 29
  • 51
0

please try below Code :

$array = array('banana','mango','apple');
$string = null;

if(count($array) > 1){

    $string =  implode(',',$array);
    $pos = strrpos($string, ',');

    $string =  substr_replace($string, ' or ', $pos, strlen(','));
}elseif(count($array) == 1){
    $string =  $array[0];
}
echo $string;
JavidRathod
  • 483
  • 2
  • 10