0

I have multiple different db strings, one for example is:

"Apples,Apples,Apples,Oranges,Apples,Oranges"

I want to represent each string dynamically as:

"I have Apples and Oranges. There are 6 in total."

Another string might be:

"Apples,Apples,Apples,Apples";

Should say:

"I have Apples. There are 4 in total."

How would I script this in PHP? Ty for help!

2

2 Answers 2

1
<?php
  $str = 'Apples,Apples,Apples,Oranges,Apples,Oranges';

  $arr = explode(',', $str);
  echo 'I have '.implode(' and ', array_unique($arr))
    .  '. There are '.count($arr).' in total.';

This should be self explanatory but for reference see: explode, implode & array_unique

Sign up to request clarification or add additional context in comments.

Comments

0

I made this test:

<?php
$data = "Apples,Apples,Apples,Oranges,Apples,Oranges";

$array = explode(",",$data); //array of elements
$count = count($array); //How many elements

$arr_unique = array_unique($array); //array of unique elements

echo "I have ".implode(" and ", $arr_unique). ". There are ".$count." in total.";
//var_dump($arr_unique); //For test
?>

PS: Check the fiddle: http://phpfiddle.org/main/code/3u4-e5v

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.