Petras99
Petras99

Reputation: 45

associative array iterating with foreach loop, php

I am making a program with php, where someone types in a word and it converts it to "big letters". I will show the code to it, and explain what i am attempting:

$bigletters = $_POST["message"];


function a(){
        echo "      X      ";
        echo "     X X     ";
        echo "    XXXXX    ";
        echo "   X     X   ";
}

function b(){
        echo "    XXXXX    ";
        echo "    X    X   ";
        echo "    XXXXX    ";
        echo "    X    X   ";
        echo "    XXXXX    ";
}

function c(){
        echo "     XXXX    ";
        echo "    X        ";
        echo "    X        ";
        echo "    X        ";
        echo "     XXXX    ";
}

$store = array("a"=>a, "b"=>b, "c"=>c, "d"=>d, "e"=>e, "f"=>f, "g"=>g,
         "h"=>h, "i"=>i, "j"=>j, "k"=>k, "l"=>l, "m"=>m, "n"=>n,
         "o"=>o, "p"=>p, "q"=>q, "r"=>r, "s"=>s, "t"=>t, "u"=>u,
         "v"=>v, "w"=>w, "x"=>x, "y"=>y, "z"=>z);

foreach ($store as $key => $bigletters){
    store[$key];
}

I have created a function for every letter of its "big" form. I have an associative array, where the string value of a letters, holds a function key towards that letter. I then want to iterate over the message received through a form from a different file, and check each character of the word against the associative array values, then display the keys of those values. I have successfully done this with python like this:

usr = raw_input("Enter a word or letter: ")
        up = usr.lower()
        for key in up:
                print
                store[key]()

I do not know how to do this with php, or even know if its possible. I also get this when i try running the program:

" Notice: Use of undefined constant a - assumed 'a' in C:\xampp\htdocs\BigLetterConverter.php on line 212

Notice: Use of undefined constant b - assumed 'b' in C:\xampp\htdocs\BigLetterConverter.php on line 212

Notice: Use of undefined constant c - assumed 'c' in C:\xampp\htdocs\BigLetterConverter.php on line 212"

Sorry if this confusing, or i am not explaining it well enough.

Any responses are appreciated!

Upvotes: 1

Views: 103

Answers (1)

rokas
rokas

Reputation: 1581

If i understand you correctly, solution in php:

$letters = str_split($_POST["message"]); // spliting string to letters array

foreach ($letters as $letter) {
    if (' ' == $letter) { continue; }
    $letter = strtolower($letter);
    echo $store[$letter]; // values from $store array
    call_user_func($store[$letter]); // calling big letter function
}

Upvotes: 1

Related Questions