1

i have this string -

$result = "ABCDE";

and i want to seperate them to 3 parts

(like part 1 = A, part 2 = B, part 3 = C..., part 5 = E)

,give a name to each of them

part 1(A) = Apple
part 2(B) = Orange
part 3(C) = Ice-cream
part 3(D) = Water
part 5(E) = Cow

then the finally output is like

Output : You choose Apple, Orange, Ice-cream, Water, Cow

or like this

$result = "ACE";

Output : You choose Apple, Ice-cream, Cow

i have tried using array

$result = "ABCDE";
$showing = array(A => 'Apple , ', B => 'Orange , ', C => 'Ice-cream , ',
 D => 'Water , ', E => 'Cow , ');
echo  $showing[$result];

but i got nothing while output, seems array is not working in fixed string.

i want to know how to do it

1
  • You have no key called ABCDE set in the $showing array, so it doesn't show anything. You'll want to take the $result string apart into individual characters and output all the array elements that intersect with this array (hint hint cough array_intersect cough). Commented Nov 7, 2011 at 6:08

3 Answers 3

1

For one line magic:

echo implode('',array_intersect_key($showing,array_flip(str_split($result))));
Sign up to request clarification or add additional context in comments.

1 Comment

codaddict & Vikk both of you are correct, great job! Just wonder i can have two accepted answer, those two codes are really great and for this time i pick Vikk.
1

You can use the function str_split to split the string into individual letters, which can later be used as keys of your associative array.

Also you don't need to add comma at the end of each string. Instead you can use the implode function to join your values:

$input = "ABCDE";
$showing = array('A' => 'Apple', 'B' => 'Orange', 'C' => 'Ice-cream',
                 'D' => 'Water', 'E' => 'Cow');
$key_arr = str_split($input);
$val_arr = array();
foreach($key_arr as $key) {
        $val_arr[] = $showing[$key];
}

echo "You choose ".implode(',',$val_arr)."\n";

Comments

0

You can access characters from a string similar to elements in an array, like this:

$string = "ABCDE";
echo $string[2];    // "C"

Technically, it's not really treating it like an array, it just uses a similar syntax.

You could use

$choices= array('A' => 'Apple', 'B' => 'Orange', 'C' => 'Ice-cream',
  'D' => 'Water', 'E' => 'Cow');
$selected[] = array();

for ($i = 0, $len = strlen($result); $i < $len; $i++) {
  $selected[] = $choices[$string[$i]];
}

echo "You have selected: " . implode(', ', $selected);

Although str_split, as others have suggested, would also work.

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.