0

I have one PHP class as below (part of the code):

class myclass{
    private static $arrX = array();

    private function is_val_exists($needle, $haystack) {
        if(in_array($needle, $haystack)) {
            return true;
        }
        foreach($haystack as $element) {
            if(is_array($element) && $this->is_val_exists($needle, $element))
                return true;
        }
        return false;
    }

    //the $anInput is a string e.g. Michael,18

    public function doProcess($anInput){

        $det = explode(",", $anInput);

        if( $this->is_val_exists( $det[0], $this->returnProcess() ) ){
            //update age of Michael
        }
        else{
            array_push(self::$arrX, array(
                'name' => $det[0],
                'age'  => $det[1]
            ));
        }

    }

    public function returnProcess(){
        return self::$arrX;
    }
}

The calling code in index.php

$msg = 'Michael,18';
myclass::getHandle()->doProcess($msg);

In my webpage says index.php, it calls function doProcess() over and over again. When the function is called, string is passed and stored in an array. In the next call, if let's say same name is passed again, I want to update his age. My problem is I don't know how to check if the array $arrX contains the name. From my own finding, the array seems to be re-initiated (back to zero element) when the code is called. My code never does the update and always go to the array_push part. Hope somebody can give some thoughts on this. Thank you.

16
  • 1
    to check if a key is in an array, check out the array_key_exists function - php.net/manual/en/function.array-key-exists.php :) Commented Apr 7, 2015 at 9:30
  • can you share some data sample of $arrX! Commented Apr 7, 2015 at 9:30
  • show us the calling code Commented Apr 7, 2015 at 9:34
  • 1
    @UserProg afraid not, you should use some external storage e.g. MySQL or Redis Commented Apr 7, 2015 at 9:44
  • 1
    @UserProg it's still separate requests, even if it's Ajax Commented Apr 7, 2015 at 9:54

3 Answers 3

1

There is a ) missing in your else condition of your doProcess() function, it should read:

    else{
        array_push(self::$arrX, array(
            'name' => $det[0],
            'age'  => $det[1]
        ));  // <-- there was the missing )
    }

Here is a complete running solution based on your code:

<?php
 class myclass{
    private static $arrX = array();

    private function is_val_exists($needle, $haystack) {
        if(in_array($needle, $haystack)) {
            return true;
        }
        foreach($haystack as $element) {
            if(is_array($element) && $this->is_val_exists($needle, $element))
                return true;
        }
        return false;
    }

    //the $anInput is a string e.g. Michael,18

    public function doProcess($anInput){

        $det = explode(",", $anInput);

        if( $this->is_val_exists( $det[0], $this->returnProcess() ) ){
            //update age of Michael
            for ($i=0; $i<count(self::$arrX); $i++) {
              if (is_array(self::$arrX[$i]) && self::$arrX[$i]['name'] == $det[0]) {
                self::$arrX[$i]['age'] = $det[1];
                break;
              }
            }
        } else{
            array_push(self::$arrX, array(
                'name' => $det[0],
                'age'  => $det[1]
            ));
        }

    }

    public function returnProcess(){
        return self::$arrX;
    }
}

$mc = new myclass();
$mc->doProcess('Michael,18');
$mc->doProcess('John,23');
$mc->doProcess('Michael,19');
$mc->doProcess('John,25');
print_r($mc->returnProcess());

?> 

You can test it here: PHP Runnable

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for the catch but the problem is still there.
@UserProg added a running sample based on your code now
page does not exists at php runnable
I already tested it and yes it worked but almost satisfy my requirement. The request is repeated and I want to maintain the value just like what SESSION does. So I believe PHP cannot do this, maybe MySQL is my best option. Thanks, appreciate it :-)
0

As I said in comments, it looks like you want to maintain state between requests. You can't use pure PHP to do that, you should use an external storage solution instead. If it's available, try Redis, it has what you need and is quite simple to use. Or, if you're familiar with SQL, you could go with MySQL for example.

On a side note, you should read more about how PHP arrays work.

  1. Instead of array_push, you could have just used self::$arrX[] = ...
  2. Instead of that, you could have used an associative array, e.g. self::$arrX[$det[0]] = $det[1];, that would make lookup much easier (array_key_exists etc.)

3 Comments

Maintain state between request Yup that is the key. If PHP is not possible, I will use MySQL then. I can maintain the state/value with SESSION but I don't want to because that might burden the memory.
@UserProg you can use $_SESSION yes, but as the name says, it's per-session storage, that is, there will be separate session (and data) for each user. If this is what you need, and not a global state, then go for it.
Understood but $_SESSION might not be my best option as the data is getting bigger and I don't want it kills the memory. MySQL is my best option. Thanks for your explanation :-)
0

Can you try updating the is_val_exists as follows:

private function is_val_exists($needle, $haystack) {
foreach($haystack as $element) {
    if ($element['name'] == $needle) {
    return true;
}
return false;
}

3 Comments

Thanks. The array is actually a multidimensional array so this will not work for me.
Its a 2D array rt? like array(0=>array('name' => 'saaaa', 'age' => 25));
my mistake, yes it is 2D array. However I want to maintain the value of the array between request. Just like a SESSION where that value is not changed when it is called over and over before it is destroyed. Appreciate your answer :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.