$fr = "hammad";
$frhammad = "nuthing";
echo $fr{$fr};
Output:
h
Whereas the expected output was
"Nuthing"
What Should be the format to echo "Nuthing"?
Because $x{$n} is standard syntax that treats the string $x as an array of characters, where $n is the numeric index position of a character in that aray. In your case the index position is identified by $fr, which is a non-numeric string, so PHP's loose typing is converting it to an integer 0, and so echoing the character at position 0... the first character of the string
EDIT
obligatory quote from the manual:
String access and modification by character
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.
Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.
EDIT #2
To answer your latest question from the comments:
how would I concatenate the name of variables as I have given in it
question?
$fr = "hammad";
$frhammad = "nuthing";
$varName = 'fr'.$fr;
echo $$varName;
or
$fr = "hammad";
$frhammad = "nuthing";
echo ${'fr'.$fr};
The correct syntax for variable-variable interpolation is:
$fr = "hammad";
$frhammad = "nuthing";
echo ${fr.$fr};
Related
I'm using PHP 7.2.2
I'm not able to understand following paragraph taken from the PHP Manual
Warning Writing to an out of range offset pads the string with spaces.
Non-integer types are converted to integer. Illegal offset type emits
E_NOTICE. Only the first character of an assigned string is used. As
of PHP 7.1.0, assigning an empty string throws a fatal error.
Formerly, it assigned a NULL byte.
I've following doubts/questions in my mind regarding the above paragraph :
What does exactly mean by 'out of range offset' here?
Whose non-integer types are converted to integer. Is it an offset or a character from a string under consideration whose type conversion is going to happen?
What does exactly mean by 'Illegal offset type'?
When does 'only the first character of an assigned string is used'?
What does mean bye the last sentence 'Formerly, it assigned a NULL byte.'? Specifically what does mean by NULL byte?
Can someone please answer all of my doubts/questions in an easy to understand language with suitable working code example?
This part of the manual is in reference to treating strings as an array of characters.
"out of range" offset means an integer index that is at a position longer than the string itself currently is, e.g. $x = "foo"; $x[10] = 'o'; results in $x becoming foo o
If a non-integer index value is used, the index value is converted to an integer before the index of the string is accessed, e.g. $x = "foo"; $y = $x[true]; results in $y taking the value of $x[1] - o
Illegal offset types are anything that couldn't normally be used as an array offset, e.g. class Foo() {} - indexing a string with $x[new Foo()]; raises a warning
The first chracter piece means that if you attempt to assign a string to the index of an existing string, only the first character of the assigned string will be used, e.g. $x = "foo"; $x[0] = "hi"; results in $x becoming hoo;
Assigning a string a value of empty string at an index now results in an error rather than assigning the "null" byte \0, e.g. $x[0] = ''
will fatal.
Here's a string for example: $string = 'word';
In PHP, a string is a byte array. You can refer to specific characters (bytes) in the string by their numeric index. An offset is in range if it is between 0 (first character) and strlen($string) - 1 (last character).
This example iterates the characters in the string, using indexes 0 through 3.
$len = strlen($string);
for ($i=0; $i < $len; $i++) {
$char = $string[$i];
var_dump($i, $char);
}
An out of range offset is any index beyond strlen - 1. This code will generate a notice:
$char = $string[4];
var_dump($char); // string ''
Notice: Uninitialized string offset: 4
Using a non-integer type as the index converts the type to an integer. The string foo (an illegal offset type) in this example will be converted to 0, so the first character of the string will be replaced.
$string['foo'] = 'c';
var_dump($string); // string 'cord'
If you try to assign a string with more than one character, only its first character will be used, and if you try to assign to an index beyond the end of the word, the interstitial indexes will be filled with spaces.
$string[5] = 'something';
var_dump($string); // string 'cord s'
I'm looking to use unpack().
This works:
$srbytes = "\x80\x3e\x00\x00";
$array1 = unpack("v",$srbytes);
This does not:
$num1 = "80"
$srbytes = "\x".$num1."\x3e\x00\x00";
$array1 = unpack("v",$srbytes);
or
$srbytes = "\x"."80\x3e\x00\x00";
$array1 = unpack("v",$srbytes);
Printing this with echo shows ASCII chars with the first full string but, the concatenated ones shows text until it passes where it was concatenated.
Comparing a full string against a concatenated ones shows false, even though they should be the same?
what is actually happening when I'm trying to concatenate
The character expansion won't work, because at the point that you do "\x" . "80" PHP already has two string literals. It can't be expected to figure that meant anything else but this.
Instead of trying to concatenate a hexadecimal value for expansion, just concatenate the actual character, by converting the hexadecimal value to a base10 integer, and passing it to chr(), which converts it to an actual byte.
$str = "";
$num1 = "80";
$str .= chr(base_convert($num1, 16, 10));
var_dump($str);
Gives you
string(1) "�"
When you actually look at the value of $srbytes in your example where you define it as a string literal "\x80\x3e\x00\x00", what you get is var_dump("\x80\x3e\x00\x00") giving you string(4) "�>", because PHP double quoted strings offer additional character expansion such as expanding on escaped hexadecimal values into bytes. However, var_dump("\x"."80\x3e\x00\x00") just gives you string(7) "\x80>", which is because the value "\x" by itself is just a literal "\x" as a string. So they aren't the same values, no.
If you want the 'literal' string use single quotes. Your issue is with escaped character sequences inside double quotes being evaluated. Example:
$srbytes = '\x'.'80\x3e\x00\x00';
echo $srbytes;
// \x80\x3e\x00\x00
var_dump($srbytes);
// string(16) "\x80\x3e\x00\x00"
$srbytes = "\x"."80\x3e\x00\x00";
echo $srbytes;
// \x80>
var_dump($srbytes);
//string(7) "\x80>"
http://php.net/manual/en/language.types.string.php
I know this question asked here many times.But That solutions are not useful for me. I am facing this problem very badly today.
// Case 1
$str = 'Test \300'; // Single Quoted String
echo json_encode(utf8_encode($str)) // output: Test \\300
// Case 2
$str = "Test \300"; // Double Quoted String
echo json_encode(utf8_encode($str)) // output: Test \u00c0
I want case 2's output and I have single quoted $str variable. This variable is filled from XML string parsing . And that XML string is saved in txt file.
(Here \300 is encoding of À (latin Charactor) character and I can't control it.)
Please Don't give me solution for above static string
Thanks in advance
This'll do:
$string = '\300';
$string = preg_replace_callback('/\\\\\d{1,3}/', function (array $match) {
return pack('C', octdec($match[0]));
}, $string);
It matches any sequence of a backslash followed by up to three numbers and converts that number from an octal number to a binary string. Which has the same result as what "\300" does.
Note that this will not work exactly the same for escaped escapes; i.e. "\\300" will result in a literal \300 while the above code will convert it.
If you want all the possible rules of double quoted strings followed without reimplementing them by hand, your best bet is to simply eval("return \"$string\""), but that has a number of caveats too.
May You are looking for this
$str = 'Test \300'; // Single Quoted String
echo json_encode(stripslashes($str)); // output: Test \\300
I have a string like any of the following:
$str = 'A001';
$str = 'B001';
$str = 'AB001';
$str = 'B0015';
....
$str = '001A';
I want to keep only 3 characters from the end of each string.
My code is like this:
$code = str_split($str);
$code = $code[1].$code[2].$code[3];
But it works for specific cases, but not for general ones! How I can get it for general ones?
I want to keep every 3 character from end of string
Simply Use substr
echo substr($str,-3); // Last 3 characters
Second parameter to this function is start, and according to the Manual
If start is negative, the returned string will start at the start'th character from the end of string.
Fiddle
Use sbstr()
echo substr($str,-3);//get last 3 char char
Or try:
echo $str[strlen($str)-3].$str[strlen($str)-2].$str[strlen($str)-1];
You need to use substr function.
All you need to do is to pass the string, and tell it where you cut the string off. If you want to cut the string off from end, you have to provide the value in negative.
substr($str, -3);
// The third argument is optional, which specifies the length of the returned string.
I have a multidimensional array that is behaving unexpectedly and I would like to know why this is, and if there is a work around. It seems that if I set something in first key of the array, it will replace the first letter of it when I declare a value in it's second key.
(I'm not sure how to properly describe the behavior but this code should help somewhat:
<?php
//Declare Array with first key and value
$test['hello'] = "Hello There";
//Echo Value
echo "HELLO TEST: ". $test['hello'] ;
//Declare Multidimensional Array using the first array key and a new key
$test['hello']['jerk'] = "JERK!";
//Echo Values
echo "<br/>HELLO TEST: ". $test['hello'] ;
echo "<br/>JERK TEST : ". $test['hello']['jerk'];
?>
That code outputs as follows:
HELLO TEST: Hello There
HELLO TEST: Jello There
JERK TEST : J
I expect to see
HELLO TEST: Hello There
HELLO TEST: Hello There
JERK TEST : JERK!
Doing this :
$test['hello'] = "Hello There";
You declare that $test['hello'] contains a string.
Then, doing this :
$test['hello']['jerk'] = "JERK!";
You declare that $test['hello'] contains an array ; and no longer a string.
Your $test['hello'] can only contain one thing.
Actually, when you are doing this :
$test['hello']['jerk'] = "JERK!";
As $test['hello'] contains a string (and not an array), I think PHP will try to access this entry : $test['hello'][0]
With 0 being the jerk string converted to an integer.
And $test['hello'][0] means the first character of the string that's in $test['hello']
See String access and modification by character in the manual, about that.
There, now, you're trying to put a whole string ("JERK!") where there can be only one character -- the first one of the existing string. And that one get overriden by the first character of the string "JERK!".
EDIT a while after : and here are the full explanations, with commented code :
// Assign a string to $test['hello']
$test['hello'] = "Hello There";
//Echo Value
var_dump($test['hello']);
// Try to assign a string to $test['hello']['jerk']
$test['hello']['jerk'] = "JERK!";
// But $test['hello'] is a string, so PHP tries to make a string-access to one character
// see http://fr.php.net/manual/en/language.types.string.php#language.types.string.substr
// As 'jerk' is a string, it gets converted to an integer ; which is 0
// So, you're really trying to do this, here :
$test['hello'][0] = "JERK!";
// And, as you can only put ONE character where ($test['hello'][0]) there is space for only one ,
// only the first character of "JERK!" is kept.
// Which means that what's actually done is :
$test['hello'][0] = "J";
// Still echo the whole string, with the first character that's been overriden
var_dump($test['hello']);
// Same as before : here, you're only accessing $test['hello'][0]
// (which is the first character of the string -- the one that's been overriden)
var_dump($test['hello']['jerk']);
// Same as this :
var_dump($test['hello'][0]);
Because it isn't an array. It's a string.
$test['hello'] = array();
$test['hello']['jerk'] = "JERK!"
You're trying to treat the string stored in $test['hello'] as an array. You're not going to be able to make $test['hello'] hold both a string ("Hello There") and another array.
From http://ca2.php.net/language.types.string.
Characters within strings may be
accessed and modified by specifying
the zero-based offset of the desired
character after the string using
square array brackets, as in
$str[42]... Non-integer [indexes] are
converted to integer... only the first
character of an assigned string is
used.
So, to answer your question. $test['hello'] is a string, so the rules of indexing strings will apply. Therefore, $test['hello']['jerk'] = "JERK!"; is equivalent to $test['hello'][0] = "J"; because the intval of 'jerk' is 0 and only the first character "J" of the assigned string "JERK!" will be used.
After, when echoing $test['hello'], you will be referring to the whole string, which now has its first character replaced by a J. Echoing $test['hello']['jerk'] is again equivalent to echoing $test['hello'][0] because the intval of 'jerk' is 0, and by the rules of indexing strings, $test['hello'][0] will return the first character of $test['hello'].
In interpretation of what you meant to do, perhaps you wanted this.
$test['hello'] = "Hello There";
$test['jerk'] = "JERK!";
print_r($test); // array('hello' => "Hello There", 'jerk' => "JERK!")
Or, to have something multidimensional...
$test['message']['hello'] = "Hello There";
$test['message']['jerk'] = "JERK!";
print_r($test);
// array('message' => array('hello' => "Hello There", 'jerk' => "JERK!"))
You are trying to declare $test['hello'] as two things: a string and an array. It can only be one or the other.
It is worth pointing out that what is happening in the code example given.
A string can be accessed like an index-based array. When you attempt to set the second level of the "array" what it is actually doing is this (since the first level is a string):
$array['levelOne'] = 'Hello.';
$array['levelOne'][(int)'jerk'];
Basically this gives (or sets) the first character of the string since 'jerk' cast as an integer is 0. If your string could have cast to a different integer then it would have returned (or set) a different character of the string.