Recursive function is not working in code-igniter [duplicate] - php

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I am using a recursive function in codeigniter but is not working properly while returning the std class object but if i am using print_r() then print_r() is printing exactly what i want.
I am not getting any warning error message.
public function get_base_id($id){
$query = $this->db->query("SELECT * FROM `m_ecommerce_category` WHERE status ='0' and id = '$id'");
$data = $query->row();
if($data->parent != 0 ){
$this->get_base_id($data->parent);
}else{
//print_r($data);
return $data;
}
}

You should return your recursive call:
if($data->parent != 0 ){
return $this->get_base_id($data->parent);
}else{
//print_r($data);
return $data;
}

Related

Recursive Function returns null value [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
Below recursive function i am trying to get array of codes. For example input 'bme4', output should be like [0]=>'bme'[1]=>'bm'[2]=>'b'. But the return value is null eventhough i can get the correct return value with var_dump().
function get_parent_cat_code($code, $category_codes) {
$parent_cat_code = substr($code, 0, -1);
if ($parent_cat_code != ''){
$category_codes[] = $parent_cat_code;
get_parent_cat_code($parent_cat_code, $category_codes);
} else {
var_dump($category_codes);
return $category_codes;
}
}
Solved!
function get_parent_cat_code($code,$category_codes){
$parent_cat_code=substr($code, 0, -1);
if($parent_cat_code!=''){
$category_codes[]=$parent_cat_code;
return get_parent_cat_code($parent_cat_code,$category_codes); //i used return for calling recursive function.
}else{
var_dump($category_codes);
return $category_codes;
}
}

PHP - Variable Safe Output [duplicate]

This question already has answers here:
Is there a better PHP way for getting default value by key from array (dictionary)?
(8 answers)
Closed 3 years ago.
I'm fetching information from a unofficial API. This API is very large and sometimes doesn't have all elements in it. I'm trying to display values from this API on my site without any errors.
What I've done is check the JSON values like so, to prevent errors:
echo (isset($json['item'])) ? $json['item'] : '';
Works, but it looks very unorganized. I've thought about creating a function to handle safe output, like so:
public function safeoutput($input, $fallback = '') {
if(isset($input)) {
return $input;
}
if(empty($input) || !isset($input)) {
return $fallback;
}
}
and then doing:
echo $engine->safeoutput($json['item'], 'Unavailable');
That unfortuanlly still outputs the Undefined variable error.
I was wondering if there's a better way to handle such information like I showed in the example.
Problem is that the key might not be set, so you would have to check it:
public function safeoutput($input, $key, $fallback = '') {
if(isset($input[$key])) {
return $input;
}
if(empty($input[$key]) || !isset($input[$key])) {
return $fallback;
}
}
Or you can have a shorter version:
public function safeoutput($input, $key, $fallback = '') {
if(array_key_exists($key, $input) && !empty($input[$key])){
return $input[$key];
}
return $fallback;
}
And call the method with the array and the key:
echo $engine->safeoutput($json, 'item', 'Unavailable');

Recursive function returning null but on var dump returns a value [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
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;
}
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.

return an array from a recursive function [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I think I need some explanations about the recursivity... I looked at some same issues over forums but it didn't help me a lot.
Here is my function :
public function tas ($nb_gift, array $winners)
{
if ( !empty( $nb_gift ) ){
$id_winner = rand( 10, 15 );
if ( !$this->_in_array_r($id_winner, $winners) ){
$existing_user = $this->getWinner( $id_winner );
}
if( !empty( $existing_user ) && $nb_gift > 0 ){
$winners[] = array( $existing_user, 'iphone5');
$this->tas($nb_gift - 1, $winners);
}
else {
if($nb_gift > 0)
{
$this->tas($nb_gift, $winners);
}
}
}
else {
//print_r($winners);
return $winners;
}
}
At the end I have an array composed of the winners. Even if the print_r works, the return doesn't give me back my array.
Does the function need some optimisation ?
You are never returning anything from the first if branch. If you call tas() initially and it goes into the first if branch, it never returns, hence the caller is never getting anything back.
Recursion is nothing special, really. You call a function, you get a result:
$winners = tas();
Simple. Internally that functions may call other functions:
function tas() {
return foo();
}
There's no restriction that tas can't call itself, but it's still bound by the same rules of returned data:
function tas() {
if (...) {
foo(); // <-- doesn't return anything
} else {
return foo();
}
}
Just substitute foo() in the above example by tas() for the same concept, but including recursion.

Return statement in PHP functions [duplicate]

This question already has answers here:
Return always return false
(3 answers)
Closed 9 years ago.
I'm having some problems with a Return statement in PHP. The thing is that, no matter what happend inside my function I always get a false value out of the function. I really think that is because of the Return statement because I try to use it in other functions and I don't get a diferent value.
public function valid_token ()
{
if (!isset($_SESSION['token']) || $this->token != $_SESSION['token'])
{
$this->errors[] = "Formulario incorrecto";
}
return count($this->errors)? 0 : 1;
}
Out of this function I always get a false value (0). The same happends when i call:
public function valid_data ()
{
if (empty($this->sectorName) || empty($this->sectorInfo) || empty($this->sectorCat))
{
$this->errors [] = "Datos incorrectos";
}
return count($this->errors)? 0 : 1;
}
Of course, I call both functions when I have already sent the form and have set the token.
Because you are just counting not checking,Try this
return count($this->errors) > 0 ? 0 : 1;
More simply,
return !$this->errors;

Categories