Max Max - 5 months ago 7
PHP Question

Replacing a line of code with an if statement

I've followed the here often recommended tutorial Build a PHP MVC Application and I ran into a line of code that was a shortened if statement using

?
and
:
. Since I'm not really familiar with this kind of short code, I tried to recreate it how I would write it.

$this->params = $url ? array_values($url) : [];


I came up with:

if(isset($url))
{
$this->params = array_values($url);
}


Is this doing the exact same thing? Or am I missing something? It works and it looks like it's doing the same, but I'd like to know for sure.

Since some of the answers depend on the state of $url, here is the full code:

<?php
class App
{

protected $controller = 'home';
protected $method = 'index';
protected $params = [];

public function __construct()
{
$url = $this->parseUrl();

if(file_exists('../app/controllers/' . $url[0] . '.php'))
{
$this->controller = $url[0];
unset($url[0]);
}

require_once '../app/controllers/' . $this->controller . '.php';

$this->controller = new $this->controller;

if(isset($url[1]))
{
if(method_exists($this->controller, $url[1]))
{
$this->method = $url[1];
unset($url[1]);
}
}

$this->params = $url ? array_values($url) : [];

call_user_func_array([$this->controller, $this->method], $this->params);
}

public function parseUrl()
{
if(isset($_GET['url']))
{
return $url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
}
}
}

Answer

if (isset($url)) will check for the presence of a set variable.

if ($url) will check for a truthy value from the variable itself.

You should use if ($url)

By the way, the code that's unfamiliar to you is called a ternary statement! It's common across a few other languages (e.g. Ruby) and it's useful to know how it works.

If you don't know what I mean about a truthy value, you should read more about boolean casting.

Comments