phpfuelphp

How do you iterate through Input::post() data?


To my understanding Input::post(); with no parameters returns an array containing all the data from a specific POST..

I am doing this $all_input = Input::post();

But then I am iterating through the array Java-like (is that how you even do it?)

for ($i=0; $i<count($all_input); $i++)
    { 
        if (strpos($all_input[$i], 'something') == true) // ERROR...

but the application crashes with error Undefined offset: 0 which I believe means that the index was not found?

I have also tried adding this to no avail:

    if (!isset($all_input))
    {
        return;
    }

If so how can you access the data to iterate through them? I know it contains data cause I can see them when I press the button during the debugging on the browser if I remove that code.

If you didn't already figure it out I am coming from Java developer and I have just started learning php so bear with me please.


Solution

  • According to this: https://fuelphp.com/docs/classes/input.html#/method_post Input::post(); will return $_POST which is an assoc array. Here is the source code, because the fuelphp's documentation doesn't cover it exactly.

    /**
     * Fetch an item from the POST array
     *
     * @param   string  $index    The index key
     * @param   mixed   $default  The default value
     * @return  string|array
     */
    public static function post($index = null, $default = null)
    {
        return (func_num_args() === 0) ? $_POST : \Arr::get($_POST, $index, $default);
    }
    

    You need to refer with your input names, so if you have an input which you call 'name', in that case you need to refer $all_input['name']. You can get your keys by using array_keys() function. Also it's better if you use foreach in this situation. Like:

    foreach($all_input as $key => $value) {
        echo 'Input key: ' . $key . ' value: ' . $value;
    }
    

    If you left the $key => you will get only the value, you can left it, if you doesn't use it inside the foreach.

    If you don't want to use foreach somewhy:

    $all_input = Input::post();
    $keys = array_keys($all_input);
    for ($i = 0; $i < count($keys); $i++) {
        if (strpos($all_input[$keys[$i]], 'something') == true) {
            // Do your stuff here.
        }
    }
    

    But I still recommend foreach if possible, it's less overhead and cleaner code.