0

I am creating a function that will return a slug based on a string entered, if a slug exists on database it will append a number with -$num, I am using codeigniter,

When I die the variable it returns the proper slug on _generate_slug it returns the correct value, but when I die on the index function it returns blank;

Here's my function

controllers/test.php

public function index()
{
  echo $this->_generate_slug('test');
}

protected function _generate_slug($string,$cntr = 0)
{
  if($cntr == 0){

        $slug = create_slug($string);

   }else{

        $slug = create_slug($string).'-'.$cntr;

   }   

   if($this->test_model->slug_exist($slug)){
        $cntr++;
        $this->_generate_slug($string,$cntr);

    }else{

        return $slug;  
    }    
}

helpers/test.php

function create_slug($string)
{
    $slug = strtolower( $string );
    $slug = str_replace('&','and',$slug);
    $slug = preg_replace('/[%\'"``]/', '', $slug);
    $slug = preg_replace('/[^a-zA-Z0-9-]/','-',$slug);
    $slug = preg_replace("/[-]+/", "-", $slug);
    $slug = trim($slug, '-');

    return $slug;
}
Zarathuztra
  • 3,215
  • 1
  • 20
  • 34
user1528706
  • 131
  • 2
  • 13
  • 2
    Why do you need to use recursion for this? Outside academics I typically see no reason to do so. Have you tried doing this iteratively to rule that out? – Zarathuztra Jun 22 '14 at 15:16

1 Answers1

0

You are getting NULL because you don't return the value in your recursion. It should be:

return $this->_generate_slug($string,$cntr);

But like it's mentioned in the comments, it's weird that you are using recursion here.

And also, I'm not familiar with the code style in CodeIgniter, but it seems a bad practice to name protected methods starting with underscore.

Denis V
  • 3,290
  • 1
  • 28
  • 40