Reputation: 3198
I have a multidimensional array below. And I am trying to get certain part of the array based on a value that is passed into the function. But for some reason it returns false even though the path
matches, it only return something if /test
is used but if I type /hello
the if
fails and it returns false
.
here is the array:
Array
(
[0] => Array
(
[name] => test_route
[path] => /test
[controller] => TestController
[action] => indexAction
)
[1] => Array
(
[name] => hello_route
[path] => /hello
[controller] => HelloController
[action] => helloAction
)
)
and here is the method:
public function getRoute($path = "", $name = "")
{
foreach($this->routes as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $this->routes[$key];
}
else
{
return false;
}
}
}
Upvotes: 0
Views: 52
Reputation: 638
I'm not sure why /test
even works. You're dealing with a multidimensional array. foreach does not do deep searches. You're going to have to modify your code to this:
public function getRoute($path = "", $name = "")
{
foreach($this->routes as $route) {
foreach($route as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $route[$key];
}
}
}
return false;
}
Upvotes: 0
Reputation: 2186
Your method exists after examining the first element. Remove the else block and put the return false outside the loop.
foreach($this->routes as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $this->routes[$key];
}
}
return false;
Upvotes: 0
Reputation: 2492
Just modifying on the code you provided , may be you should try something like this :
public function getRoute($path = "", $name = "")
{
foreach($this->routes as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $this->routes[$key];
}
}
return false;
}
Upvotes: 2