E
E
Elidomadto2015-01-07 22:17:41
PHP
Elidomadto, 2015-01-07 22:17:41

How to know if an array key is the last one?

Hello!
There is this code:

class Handler {
  public static function go_to($url, $parametrs = NULL)
  {
    if (isset($parametrs))
    {
    foreach ($parametrs as $key => $value)
    {
      if (count($parametrs) > 1)
      {
          $params .= $key.'='.$value.'&';
      }
      else
      {
        $params = $key.'='.$value;
      }
    }
    }
    if (isset($parametrs))
    {
      return header('Location: /'.$url.'?'.$params.'');
      exit();
    }
    else
    {
      return header('Location: /'.$url.'');
      exit();
      }
  }
}

Usage:
<?php
Handler::go_to('index', array('succcess' => '20', 'r' => '29312'));
?>

It is intended for redirecting by the link specified in the $url variable with the specified $params. The problem is that at the end of the url in the address bar remains & (which is not surprising). I want to remove it. I suppose that for this you need to check if the array key is the last one. But how can this be done?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Aksentiev, 2015-01-07
@Elidomadto

Discover: http_build_query

S
Stanislav, 2015-01-07
@mzcoding

With the end() function

if (count($parametrs) > 1){
         if(end($parametrs) === $value)
           $params .= $key.'='.$value;
         else
          $params .= $key.'='.$value.'&';
      }

P
Prosto, 2015-01-08
@Prosto

Is it possible through implode()?
foreach ($parametrs as $key => $value)
{
$params = implode('&', array($params, $key.'='.$value));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question