How to find how many keys are in array?

I did this to find out how many value in Array. Unfortunately, there are always 1, actually there are many.

$forExample = '{"sik1":"hello","sik2":"world","sik10":"today","sik41":"yesterday"}';

In the example above, there are a total of 4 values.

I tried it;

$test = json_decode($forExample);
		$rows = count($test); 

		for ($valueCount = 0;
		     $valueCount < $rows;
		     $valueCount ++) {
			if ($rows) {
				if ($test->{'sik'[$valueCount]} != '') {
					echo $test->{'sik'[$valueCount]};
				}
			}
		} 

Where do I make the mistake?

My PHP isn’t so great, but this doesn’t look right.
I’m thinking it should be $test->{'sik' . $valueCount} instead

I tried, but it return empty.

Did you change that in both the if and the echo statements?

I tried debugging it in the PHP shell, but got nowhere with it. It’s another reason I don’t use PHP.

I’m starting to see the problem. Did you pay attention to the warnings?

php > $forExample = '{"sik1":"hello","sik2":"world","sik10":"today","sik41":"yesterday"}';
php > $test = json_decode($forExample);
php > $rows = count($test);
PHP Warning:  count(): Parameter must be an array or an object that implements Countable in php shell code on line 1

Warning: count(): Parameter must be an array or an object that implements Countable in php shell code on line 1

That’s because decode_json returns an object by default. You need to pass the extra parameter to tell it to return an array.

json_decode($forExample, true)

Then with the other fix I mentioned, it should work.

Thank you for warning. I replaced sizeof($test) instead count($test)

So I can get the number of values in array but I still can’t print the value.

Can you paste your new code please?

Updated // add echo $valueCount; // Result: 01

       $test = json_decode($forExample, true);
       $rows = sizeof($test); 

       echo $rows; // Result: 4

        for ($valueCount = 0;
             $valueCount < $rows;
             $valueCount ++) { 

             echo $valueCount; // Result: 01

                if ($test->{'sik' . $valueCount} != '') {
                    echo $test->{'sik' . $valueCount};
                }
            
        } 

Ah, now it’s because you’re trying to use property access syntax, when you need to use array access syntax because now it’s an array and not an object. Try this instead:

$test['sik' . $valueCount];

I have noticed my mistakes thanks to you.

I will use the code on this page to solve the problem