Trying to convert some form code into a function

I have some often used lines of code that either display the posted field value or the value in the database.

    if ($missing || $errors) {
        echo 'value="' . html($field_name) . '"';
    } else {
        echo 'value="' . html($admins["field_name"]) . '"';

I managed to find the solution to get the first echo working in a function, but not the 2nd one…

This is how far I got…

function display_value($array_name, $field_name) {
    global $missing, $errors, $$field_name;
    if ($missing || $errors) {
        echo 'value="'. html($$field_name) .'"';
    } else {
        echo 'value="'. html( ??? ["{$field_name}"]) .'"';

I suspect it should work except for the ??? part where whatever I try fails.
The error is always on that line. The html() function and $missing || $errors seem not part of the problem.

In this case I would wanna use it inside an input like

<?php display_value("admins", "field_name"); ?>

Thanks for any pointers! : )

out of curiousity, why not… just… pass the array?

If you want to get variable name from other variable then use double $:


As I see you’ve already done it with $$field_name

To me, a function shouldn’t rely on global variables to make it work - to be any use, it needs to have everything passed in as parameters. I’m thinking mainly of a function you’d use in more than one project so maybe that’s a bit over the top, and it may just be a personal view.

@droopsnoot: I feel pretty much a beginner still so I welcome all views. I had not considered your point since that line of thinking is not yet completely familiar to me…

In any case, I would hope that since the $missing and $errors vars are reset on every page where it matters, it does not harm and seems better to me than having 2 extra parameters for every form input function (for a 25 input form that’s 50 words adding to file size and messing up my view :blush: ).

@StarLion and megazoid …

BTW: Whenever I tried array functions inside my function (to try and get ‘field_name’), I often got errors as if this (admins[‘field_name’]) is not an array…? :frowning:

I’m also still looking for the difference of $$var and ${$var}, and the use of the latter.
Maybe that would get me there…

In the mean time I am passing admins[‘field_name’] as a parameter and got that to work. Thx!

However, I would like to pass no more than this parameter and I haven’t found yet how I can get ‘field_name’ out of admins[‘field_name’] and assign it to a variable.

I’m currently using and calling display(admins[“field_name”], “field_name”);

function display($array, $field_name) {
        global $missing, $errors, $$field_name;
        if ($missing || $errors) {
            echo 'value="'. html($$field_name) .'"';
        } else {
            echo 'value="'. html($array) .'"';

This seems to be working, but again: I’d like to drop the 2nd parameter and get field_name out of admins[‘field_name’]…

I am unaware of there being a PHP html() function.

A lot may depend on what that returns.

If always an array maybe you could do a
foreach($array as $key => $val)
and get what you need inside that?

It’s from Kevin Yank’s book:

function html($text)
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');

I keep getting the sigal that something like $admin[“name”] seems not to be an array and I don’t know why…
If I do …

$admins['name'] = 'John';

isn’t that an array?

If it is, isn’t ‘name’ the key, and couldn’t I simply put the key into a variable with …

$key = key($admins['name']);

That’s all I want at this moment, assign ‘name’ to a variable, which will probably allow me to use a function with just one parameter.

$admins is the array. $admins['key'] could be another array (i.e. in a multi-dimensional array) but in this case it is the String “John”.

html() takes a String and returns a (sanitized) String.

There are a lot of array functions and some are not so easy to understand

Maybe something like this will help

while ($form_value = current($admins)) {
    if ($form_value == 'John') {
        echo key($admins).'<br />';
1 Like

Both cases work equal. There is only visual difference. It’s easier to catch curly braces with eye than just double $ sign.

That’s exactly my point, though - you’re hoping those global vars are on every page, where if they were parameters you wouldn’t need to. But you know what I mean - if it’s a function you’ll only ever use in this specific project and it would “cost” more (in size and/or complexity) to pass everything in, there’s an argument yours is the better way. It’s just a personal dislike of mine - sometimes it’s way more complex to pass in everything you need.

Not… quite true. {}'s are used to solve ambiguity problems.


Did I ask for the value of the variable who’s name is in $array[1]? or am i looking for an array at $$array and then want it’s second value? Ambiguity is a nono. So, we solve it with curly braces.

function display_value($array_name, $field_name) { 
  return html((($missing || $errors) ? $$field_name : ${$array_name}[$field_name]));

As far as doing it in one parameter: No. Unless you specify “it will always be the $admins array”, you have to send two parameters: Which array to index, and the field you’re indexing. Sending the function $admin[$field_name] as a parameter sends the function the value of that array element - in this case “John” - and the function has no concept of “John” being part of an array anymore - it’s just a string.

1 Like

Ah, sure, you’re right. I’m forgot about that aspect.

Thanks! I understand that now.

I understand your function as well, but it still took me a few hours to get it working… I needed to give the function access to 4 globals and decided to stay with the echoing and renamed the function after that.

function echo_value($array_name, $field_name) {
    global $missing, $errors, ${$array_name}, $$field_name;
    echo 'value="'. html((($missing || $errors) ? $$field_name : ${$array_name}[$field_name])).'"';

Have you just missed why I need the globals, found it evident, or do you think I’m doing something wrong somewhere?
I’m not doing too much special stuff, is my guess though. Just the basics of getting $_POST values or all database columns for one user and displaying the values in the form.

BTW: if $missing and $errors were declared as global somewhere before they were assigned values, I guess I might not need to declare …

global $missing, $errors; // (etc)

inside the function, but they are not; so that statement is so the function can have access to them, even though they are not global vars, is what I understood…

Or am I creating globals with this as well, and is that what others try to warn me for?

[quote=“droopsnoot, post:11, topic:197850”]
you’re hoping those global vars are on every page[/quote]
I’m confident that my current setup would give no problems. What I was hoping was that my way wasn’t too much of a bad practise (and currently I don’t think or am not aware that it is very much).

It is the intention to keep using it for many forms in the future and “build my style” with these functions.

The first piece of code may look familiar to people that read David Powers’ first PHP book and to me it therefore seemed a standard way of handling this situation that is now a bit ingrained in me.

I just wanted less of a timeconsuming mess on the page and did read here from someone experienced that functions are used for this kind of thing (or even to make whole input blocks, or also views/templates I will learn about later).

So as long as I’m gonna keep $missing and $errors for my form errors and validations, I’m pretty happy with the still flexible 2 parameter function.

:sunny: Special Thanks to all contributors!

To me it isn’t a matter of “will global variable work” but more “do I absolutely need to”

But I am biased.

Some “common, practices” make me shake my head in wonder.

I try to avoid using globals as much as I avoid using eval, buffer functions to side-step header errors , @ error suppression and other rg.

But if you know you must then of course, you must

I think I may not be aware that I’m creating a global variable…

As explained to StarLion, AFAIK the vars $missing and $errors are originally not defined as global ones. So in my mind the ‘global’ declariation inside the function is simply to give the function access to these in my mind non-global vars.

But if this is also making global vars of them(?), then you may be right and I may be creating a monster… :wink:

I’ve never needed to globalize so many (read: all) variables in a function.

That said, I dont know that i’ve ever created a function that is 1 line long and is only a conditional-call of another function. So… yeah. If it works for you, then it works. There’s not an inherent significant problem in doing it this way, just looks odd.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.