strlen on array returns 5 in php - php

From the docs -
int strlen ( string $string )
it takes string as a parameter, now when I am doing this-
$a = array('tex','ben');
echo strlen($a);
Output -
5
However I was expecting, two type of output-
If it is an array, php might convert it into string so the array will become-
'texben' so it may output - 6
If 1st one is not it will convert it something like this -
"array('tex','ben')" so the expected output should be - 18 (count of all items)
But every time it output- 5
My consideration from the output is 5 from array word count but I am not sure. If it is the case how PHP is doing this ?(means counting 5)

The function casts the input as a string, and so arrays become Array, which is why you get a count of 5.
It's the same as doing:
$a = array('tex','ben');
echo (string)$a; // Array
var_dump((string)$a); // string(5) "Array"
This is the behavior prior to PHP 5.3. However in PHP 5.3 and above, strlen() will return NULL for arrays.
From the Manual:
strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.
Prior [to 5.3.0] versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.

Use
$a = array('tex','ben');
$lengths = array_map('strlen',$a);
to get an array of individual lengths, or
$a = array('tex','ben');
$totalLength = array_sum(array_map('strlen',$a));
to get the total of all lengths

The array is implicitly converted to a string. In PHP this yields the output Array, which has 5 letters as strlen() told you.
You can easily verify this, by running this code:
$a = array('tex','ben');
echo $a;

Related

Convert array of values into a single float value in PHP?

I have an array with these values (when the array is printed with print_r();
Array:
[0] => 66
[1] => 233
[2] => 204
[3] => 205
The values in hex are:
Array:
[0] => 0x42
[1] => 0xE9
[2] => 0xCC
[3] => 0xCD
What I'm looking to do is to turn this 4 byte array into a float value. If I use implode(); to turn the array into a value, it just combines the string into 66233204205 instead of 0x42E9CCCD which are not similar. Thus I can't use floatval(). PHP is new to me, and so is using string values instead of the actual bits, like I can in C.
What I'm thinking is to some how implode() it with the hex values, instead of those integer numbers, and then use floatval().
Any ideas guys?
EDIT:
Just so it's a little clearer, I should be obtaining 116.900 as the result
You have to do a simple math operation to concatenate hex values of the array one after the other. The algorithm would be like this:
Assign the first hex value of the array to a resultant variable, $concat in this case.
Use a for loop to loop through the array from 2nd element till nth element
In each iteration of the loop left shift 8 times the existing hex value of the resultant variable and place the new hex value in the least significant 8 bits of the resultant variable.
// Suppose $array is your original array
$concat = $array[0];
$count = count($array);
for($i = 1; $i < $count; $i++){
$concat = ($concat << 8) + $array[$i];
}
// display concatenated hex value: 42e9cccd
var_dump(dechex($concat));
// Now do your operation on the concatenated hex value
Here's a demo, https://eval.in/844793
Revised Answer with ....
Performing math with hex strings used to be a feature supported in PHP. Now with PHP 7, a hex string only represents a string of characters and no longer is recognized as containing a numeric value. If you attempt to do math with it, the result is zero. Consider the following code:
<?php
$arr = [66, 233, 204, 205];
$res = array_reduce( $arr, function($c,$i) {
$c.=dechex( $i );
return $c;
});
$temp = "0x" . $res; // 0x42e9cccd
var_dump($temp + 0);
See demo
This code attempts to provide the hex string a mathematical context by adding zero to the value contained in $temp. This code works until PHP 7 because the powers that be determined that hexstrings created more problems than they were worth; see this RFC and the Manual:"Hexadecimal strings are no longer considered numeric".
Concatenation, being a string operation, creates the example's hex string whose direct usage proves unwise in a math operation. A notice will be emitted (in PHP 7.1), complaining as follows:
Notice: A non well formed numeric value encountered
You may suppress displaying this notice, but the resulting sum will be zero in PHP 7. When the code functions correctly in PHP 5.6, the result of 1122618573 seems wrong, certainly far too large to cast as a float and obtain the value that the OP seeks.
... A Bona Fide Work-Around
<?php
$arr = [66, 233, 204, 205];
$res = array_reduce( $arr, function($c,$i) {
$c.=dechex( $i );
return $c;
});
$temp = "0x" . $res;
$int = filter_var( $temp, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX );
if (false === $int) {
throw new Exception("Invalid integer!");
}
$arr = (unpack('f', pack('i', $int )));
$f = array_pop($arr);
printf("%.3f",$f);
See demo
PHP will recognize the numeric hex string that array_reduce() yields if you use filter_var() with the indicated parameters. In this fashion, you may obtain an integer evaluating as 1122618573. The key thing rather than the integer's value is its binary bit pattern. Borrowing from the official answer here, the code needs to pack $int into a binary string, which it subsequently will unpack as a float -- almost. That result will be returned as an array with just one element. After popping off and capturing that element's float value, printf() displays 116.900.
This appends the values of the array to eachother (in hexadecimal). PHP's dechex() function.
http://php.net/dechex
dechex — Decimal to hexadecimal
$b = [66,233,204,205];
$a = dechex($b[0]);
for($x = 1; $x < count($b); $x++) {
$a = $a . dechex($b[$x]);
}
echo $a; // $a = 42e9cccd
You didn't specify if your array represents an integer, if is the integer part of the floating point value, or is the entire number represented in IEEE 754 format.
Anyway, I would suggest you to take a look at the "pack" function.
$value = pack('i', your_value);
HERE you can find the documentation: basically you have to provide the type you want to obtain, along with your value(s), of course.
Also PHP is NOT a strongly typed language, so you don't have to distinguish integer from floats, in this case. You can treat integer like floats, and viceversa. But if you want to be 100% sure, just do something like this:
$value = floatval(pack('i', your_value));
This is, of course, machine dependent, but I don't know of any machine running PHP that doesn't use IEEE 754 floats.

php variables, strings and arrays: associative array returns first letter of string

I understand that, with a sting assigned to a variable, individual characters can be expressed by using the variable as an indexed array, but why does the code below, using an associative array, not just die with missing required? Why does 'isset' not throw FALSE on an array key that definitely doesn't exist?
unset($a);
$a = 'TESTSTRING';
if(!isset($a['anystring'])){
die('MISSING REQUIRED');
}else{
var_dump($a['anystring']);
}
The above example will output:
string(1) "T"
EDIT:
As indicated by Jelle Keiser, this is probably the safer thing to do:
if(!array_key_exists('required',$_POST)){
die('MISSING REQUIRED');
}else{
echo $_POST['required'];
}
What PHP is doing is using your string as a numeric index. In this case, 'anystring' is the equivalent of 0. You can test this by doing
<?php
echo (int)'anystring';
// 0
var_dump('anystring' == 0);
// bool(true)
PHP does a lot of type juggling, which can lead to "interesting" results.
$a is a string not an associative array.
If you want to access it that way you have to do something like this.
$a['anystring'] = 'TESTSTRING';
You need to use array_key_exists() to test if a key exists
The working of isset is correct in your case.
Because $a is a string, the index-operator will give you the specified char in the string at the declared position. (like a "Char-Array")
A small example:
$a = 'TESTSTRING';
echo $a[0]; // Output: T
echo $a[1]; // Output: E
// ...
This will output the first and the second character at index 0 and 1 of the string.
And because the index-operator always expects an integer value on strings. The given value will be automatically casted to an integer. You can see this, when you cast the string to an integer, like this:
echo (int) 'TESTSTRING'; // Output: 0
For char-access on strings, also see the PHP-Manual.
Try enabling PHP to show all errors by using error_reporting(E_ALL);
This should give you a warning saying you are using an illegal offset. PHP therefore automatically assumes you are looking for the first element in the array or letter in this case.
it works as expected for... it returned false... but when I force it to return true ... itz throws an error saying illegal offset somekind.... but still output the first string.... as anystring casted as int equals to 0.. check the version of php you are using bro... I used notepad++ to create the php file... no special ide...

PHP : is it dynamich thing or any thing else

Anyone can explain it why is it true
$a = Array('b' = > 'okokokok');
if ( isset( $a['b']['ok'] ) ) {
echo $a['b']['ok']; // Print 0
} else {
echo "else";
}
This was for backward compatibility with PHP 4 (see PHP Bug #29883). When casting a string to an integer, and the string is not a valid integer, it becomes 0 (zero). The letter "o" is printed because that is the character at offset 0 in the string.
In PHP 5.4, the behavior intentionally changed (see PHP Bug #60362); that PHP version instead prints "else".
First of all, it doesn't print '0', but lowercase 'o'.
Try this:
$string = 'abc';
echo $string['omgwhysuchkeyworks'];
It will print 'a'. That is because it seems in PHP when you try any key (other than numeric) on string variable it will return the first character of the string. That's also why isset($a['b']['ok']) returns true.
And it might be an issue of the PHP version. Perhaps on newer version it will work as intended (it will write 'else')
It prints else. 'ok' is no array index but a value on index 'b' of array $a:
Array
(
[b] => okokokok
)
See http://ideone.com/50EhGW
$a = Array('b' = > 'okokokok');
if ( isset( $a['b']['ok'] ) ) {
echo $a['b']['ok']; // Print 0
} else {
echo "else";
}
When you have a string ,you can treat it as array. its indexes would be numerical, starting from zero to string length minus one. But if you try to pass a string as index (ok in this case) , PHP tries to convert it to integer , evaluates it as zero(intval('ok')). On systems with php 5.4, it treat differently and checks the key itself and doesn't do the converting .So, in one system it may print else and on the other it prints o.

PHP and access to string like to assoc array

Is that logical behavior?
$str = 'string';
$res = $str['some_key'];
echo (int)isset($str['some_key']); // 1
echo $res; // 's'
It's a bug or unclear feature?
It is a "feature". When using $string[$index], $index is treated as integer, so 'some_key' is converted to 0. That's also why you get 's' (first letter of $str) in $res.
$str = 'Lorem';
var_dump($str['key']); // L, because (int)'key' is 0
var_dump($str['0key']); // L
var_dump($str['1key']); // o, because (int)'1key' is 1
var_dump($str['2key']); // r
var_dump($str['3key']); // e, because (int)'3key' is 3
var_dump($str['4key']); // m
var_dump($str['5key']); // Notice: Uninitialized string offset: 5 in sandbox\index.php on line 20
Accessing strings like arrays is a feature.
Strings only have numeric offsets, any "key" you use is cast to an int.
Non-numeric strings cast to the int 0.
Hence $str["foo"] is equivalent to $str[0].
So there is a logic, whether you want to call it logical or not is up to you.
But if you're accessing strings with string keys, something's wrong with your code anyway. ;-)

PHP Does if (count($array)) and if ($array) mean the same thing?

In PHP, will these always return the same values?
//example 1
$array = array();
if ($array) {
echo 'the array has items';
}
// example 2
$array = array();
if (count($array)) {
echo 'the array has items';
}
Thank you!
From http://www.php.net/manual/en/language.types.boolean.php, it says that an empty array is considered FALSE.
(Quoted):
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Since
a count() of > 0 IS NOT FALSE
a filled array IS NOT FALSE
then both cases illustrated in the question will always work as expected.
Those will always return the same value, but I find
$array = array();
if (empty($array)) {
echo 'the array is empty';
}
to be a lot more readable.
Note that the second example (using count()) is significantly slower, by at least 50% on my system (over 10000 iterations). count() actually counts the elements of an array. I'm not positive, but I imagine casting an array to a boolean works much like empty(), and stops as soon as it finds at least one element.
Indeed they will. Converting an array to a bool will give you true if it is non-empty, and the count of an array is true with more than one element.
See also: http://ca2.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

Categories