PHP - why doesn't count() work like strlen() on a string? - php

A string is an array of characters, correct? If so, then why does count() not produce the same result as strlen() on a string?

Unless it is an object, count casts its argument to an array, and
count((array) "example")
= count(array("example"))
= 1

A string is an array of characters in C, C++ and Java. In PHP, it is not.
Remember that PHP is a very loose language, you can probobly get a character from a PHP string with the []-selector, but it still dosn't make it an array.

count() counts the number of entries in an Array.
$test = array(1,2,3);
echo count($test);
Output: 3
Why would you want to use count() on a string when strlen() can do that? Are you not sure if your input is a string or an array? Then use is_array() to check that.

How exactly a string is being handled internally by a specific programming language, must not necessarily mean you can handle it equally to therefore "related" data types. What you describe may be possible in plain C. However PHP is not C and so is not following the same characteristics.

Strings are just a series of charactes, and count only counts number of elements in an array.
using $string[$index]; its just a shortcut kinda of thing to help you find Nth character,
you could use count(explode('',$string)); which presumably is what strlen does
so lesson for today is
count == array length
strlen == string length

count gets the number of elements in an array, srtlen gets the length of a string. This is in the docs:
http://php.net/manual/en/function.strlen.php

count is more preferabaly user for array value count
strlen its count only the no of char in str.....

Related

PHP Eval variable and set another variable

If I have a string like this:
0+1+0+0+0+0+0+1+0+1+1+1+1+0+0+1+0+1+1+1+1+0+0+1+0+0+1+0+0+0+0+0+0+1+1+0+1+1+0+0+0+1+1+0+1+1+0+1+0+1+1+0+0+0+0+1+0+1+1+0+1+1+1+1
I need it do actually do the math.
So if $a = '0+1+0+0+0+0+0+1'
It would set another variable and set it as:
2
You should never eval strings if you can help it. There's a trivial sane solution for parsing and summing this particular string:
$string = '0+1+...';
$result = array_sum(explode('+', $string));
If you want to support more possible operations than just +, you'd do a slightly more complex preg_split, then loop over the resulting items and evaluate each individual operator and sum or subtract or whatever based on the encountered operator in a loop.
You can use the php eval function as follows.
<?php
$string="0+1+0+0+0+0+0+1+0+1+1+1+1+0+0+1+0+1+1+1+1+0+0+1+0+0+1+0+0+0+0+0+0+1+1+0+1+1+0+0+0+1+1+0+1+1+0+1+0+1+1+0+0+0+0+1+0+1+1+0+1+1+1+1";
eval("\$val=$string;");
var_dump($val);
?>
This will output int(31) which is the sum of the integers in the string

Counting Array Returns One Digit Higher

I'm trying to count a php array.
I have my code successfully counting it, but the value is returning one digit higher than what my array is.
I have tried using -- when echoing my array, but that doesn't work.
Here is my code so far:
$quotes[0] = "Volvo";
$quotes[1] = "BMW";
$quotes[2] = "Toyota";
$quotesCount = count($quotes);
echo ($quotes[rand(0, 2)]);
echo $quotesCount--;
When it count's it returns "3" which makes sense because there are three items, but how do I subtract a number when it echos so that it reflects the the largest digit in the array?
What you tried with the echo $quotesCount--; is almost doing what you want it to. What you missed though is how the -- works. You can place it either infront of the variable or behind it - and that makes a difference.
To get the full version, read this: http://php.net/manual/en/language.operators.increment.php
But the short version is that you could potentially do this:
echo --$quotesCount;
Which will show you the value you want.
However this is still not really true - you are confusing array keys with the count of elements in an array.
If your array had non-sequential keys (1,3,5) for example, that code would return 2 - which is certainly not the highest key.
You can get a nice stepping stone to the key itself by using http://php.net/manual/en/function.array-keys.php - then you can reference the actual key itself by its order in the array.
You can use array_max($quotes) z this will return the highest key in the array.
Hey" you should array_max($array) in this case.
array_max is an array function which returns the highest value of an array.
That's it,
Keep Coding :)

Testing returned values for duplicates

I've got a method that returns a string with predefined length of random alpha numbers.
I just let it run until it comes across a duplicate and breaks out of the loop and display the amount of generations it took before a duplicate was generated.
The loop numbers will be in the millions, and I am wondering if this really is good and efficient of testing it?
You can use array_search
The function return the string and store it to an array.
Then use array_search to see if it is not FALSE and loop.
Put The generated strings into an array as a key before outputting them.
$array[$alpha_string] = (isset($array[$alpha_string])) ? $array[$alpha_string] + 1 : 1;
Then check which items have a count > 1.

PHP - elegant (fast) way to access elements counting from end of array?

I've got an array where I want to grab the "negative three" element regardless of array length. (If that doesn't make sense throw out a comment and I'll clarify).
The obvious way to do it is $arr[count($arr)-4] but this feels clunky.
Is there a quick, elegant way to do this?
UPDATE
Still fiddling, any thoughts regarding this?
array_slice($arr,-4,-3);
The obvious way returns the single value you want in constant time, assuming you have numeric indexes. The array size is known to PHP already, it just jumps to the offset you want and gives you the result.
array_slice does many times as much work, comparing the array size to your offset, computing the loop conditions, creating a new array to store the slice, looping over the portion of the existing array, copying the values into the new array, then returning that array to you.
http://lxr.php.net/opengrok/xref/PHP_TRUNK/ext/standard/array.c
Yes there is:
Try something like this:
$newArray = array_slice($array, -3);
you could use $last = end($arr); then use prev($arr); twice to get 2 other elements.
Oh, and check if these return FALSE, in case you don't have at least 3 elements.
array_slice()?
array_slice($a, -3)
Try array_slice() function, giving negative offset as a second parameter.

php associative array values always set?

$test['test'] = 'test';
if(isset($test['test']['x']))
return $test['test']['x'];
This statement returns the first character of the string in $test['test'] (in this case 't'), no matter what is specified as dimension 2.
I can't wrap my head around this behavior. I use isset() all the time. Please advise.
This happens because you're not indexing an array, you're indexing a string. Strings are not arrays in PHP. They happen to share a concept of indexes with arrays, but are really character sequences even though there is no distinct char data type in PHP.
In this case, since strings are only indexed numerically, 'x' is being converted into an integer, which results in 0. So PHP is looking for $test['test'][0]. Additionally $test is only a single-dimensional array, assuming 'test' is the only key inside.
Not really relevant to your question, but if you try something like this you should get 'e', because when converting '1x' to an integer, PHP drops anything that isn't a digit and everything after it:
// This actually returns $test['test'][1]
return $test['test']['1x'];
If you're looking for a second dimension of the $test array, $test['test'] itself needs to be an array. This will work as expected:
$test['test'] = array('x' => 'test');
if (isset($test['test']['x']))
return $test['test']['x'];
Of course, if your array potentially contains NULL values, or you want to make sure you're checking an array, use array_key_exists() instead of isset() as sirlancelot suggests. It's sliiiiightly slower, but doesn't trip on NULL values or other indexable types such as strings and objects.
Use array_key_exists for testing array keys.
It's returning 't' because all strings can be treated as arrays and 'x' will evaluate to 0 which is the first letter/value in the variable.

Categories