is string an array in php - php

you can do numeric index in string like in array.
ex.
$text = "esenihc gnikcuf yloh";
echo $text[0];
echo $text[1];
echo $text[2];
...................
...................
...................
But if you put string in print_r() not same will happen like in array and you cant do count() with string.
I read the documentation and it says.
count()
return 1 if not an array in the parameter
print_r()
if string is in parameter it just prints that string.
this is not the exact word but something like this.
Why both these functions dont treat string same as an array?
So final question is string an array?

Unlike for example C, PHP has an inbuilt string datatype. The string datatype allows you array-like access to the single characters in the string but will always be a string. So if you pass it to a function that accepts the mixeddatatype this function will determine the datatype of the passed argument and treat it that way. That is way print_r() will print it in the way it was programmed to output strings and not like an array.
If you want a function that works does the same as count for arrays have a look at strlen.
If you want you can "turn" your string into an array through str_split.

A string is an array if you treat it as an array, eg: echo $text[0], but print_r Prints human-readable information about a variable, so it will output that variable.
It's called Type Juggling
$a = 'car'; // $a is a string
$a[0] = 'b'; // $a is still a string
echo $a; // bar
To count a string's length use strlen($string) then you can for a for()

no a string is no array
A string is series of characters, where a character is the same as a byte and An array in PHP is actually an ordered map. A map is a type that associates values to keys.

simply everything in the sense every variable in PHP is an array.

Maybe too late but:
<?php
$text = "esenihc gnikcuf yloh";
$arrText = explode(" ", $text);
foreach($arrText as $word) {
echo $word . "<br>";
}
?>

Related

php max function returns min value from array

this is my first post. sorry if i did something wrong...
anyways i have a file that gets updates by php and this is EXACTLY it:
31\n
127\n
131\n
124\n
144\n
142\n
133\n
133\n
9\n
0\n
22\n
18\n
i made this script in php:
$logContents = file_get_contents("logs/mainlog.txt");
$logitemArray = explode("\n", $logContents);
echo max($logitemArray);
but it echos 9. why? it said in the php documentation that max() should return the biggest value in the array
thanks in advance
explode() returns an array of strings, so they're being compared lexicographically. You need to convert them to numbers so that max() will compare them numerically.
$logitemArray = array_map('intval', explode("\n", $logContents));
echo max($logitemArray);
BTW, you can use the file() function to read a file directly into an array of lines, instead of using file_get_contents() followed by explode().
$logitemArray = array_map('intval', file("logs/mainlog.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
Like the comments have said, it's because 9 is the largest lexigraphical value. If it said 900 it would still be the same.
This is because when you split the string with explode you get an array of type string. The following code will convert the elements in the array to integers which should give expected behaviour.
$logitemArray = array_map('intval', explode("\n", $logContents));

how to convert letters into array in php

i am trying to convert letters into array.
All the letters are coming from mysql results randomly
for($column=0;$column<8;$column++){
echo '<div class="'.bluexyz.'">'.
$field1 = mysql_fetch_object($sql)->code
.'</div>';
}
each individual letter is a div named bluexyz.
now i want to convert these letters into array.
i have used explode inside the forloop which is not working.
$array = explode('\n',$field1);
it is placing all the letters in the array index of [0]. i want to place a one letter in the one index.
It'd be easier if you provide a clearer explanation and provide an example of what you're fetching and what exactly you're expecting the output to be.
From what I understand, you're trying to convert the $field1 string into array.
You could use str_split() function here.
Try this:
$array = str_split($field1);
echo "<pre>";
print_r($array);
echo "</pre>";
Hope this helps.

Parse a string in php

I am wondering how I can parse this string to get a certain name or string. What I need to parse is:
items/category/test.txt
To get it with out test.txt of course there will be different names so I can't just replace it.
I need the result to be:
items/category/
Also how can I parse it to get /category/ only?
Use PHP's pathinfo() function:
http://php.net/manual/en/function.pathinfo.php
$info = pathinfo('items/category/test.txt');
$dirPath = $info['dirname'];
// OR
$dirPath = pathinfo('items/category/test.txt', PATHINFO_DIRNAME);
// Output: items/category
Use explode to get the above string as array
$string = "tems/category/test.txt";
$string_array = explode("/",$string);
print_r($string_array); // Will Output above as an array
// to get items/category/
$var = $string_array[0].'/'.$string_array[1];
echo $var; //will output as items/category/
$var2 = '/'.$string_array[1].'/';
echo $var2; //will output as /category/
I believe your best chance is explode("/","items/category/test.txt") .
This will splice the string every time it finds / returning an array, whereas implode (join is an alias of it) will join an array of strings, so
$spli=explode("/","items/category/test.txt");
implode($spli[0],$spli[1]);
Should do the trick for the first case, returning items/category
For category alone, $spli[1] is enough.
Of course, you may pass the string as a variable, for instance
$foo="items/category/test.txt;"
explode("/",$foo);
etc.

PHP manipulate string (find/replace if value exists)

I have a text string that is set in a variable to a value like these:
$str = 'type=showall'
or
$str = 'type=showall&skip=20'
$str = 'type=showall&skip=40'
$str = 'type=showall&skip=60'
and so on.
I need to check to see if there is a "skip" value present in the string, and if so replace it with a new number that is stored in a $newSkip variable and keep the string the same except for the change to the skip value.
For example if the string was:
$str = 'type=showall&skip=20'
and
$newSkip = 40
then I would like this to be returned:
$str = 'type=showall&skip=40'
If there was no skip value:
$str = 'type=showall'
and
$newSkip = 20
then I would like this to be returned:
$str = 'type=showall&skip=20'
I'm fairly new to PHP so still finding my way with the various functions and not sure which one/s are the best ones to use in this scenario when the text/value you're looking for may/may not be in the string.
PHP has a handy function called parse_str() which accepts a string similar to the one you have, and returns an array with key/value pairs. You'll then be able to inspect specific values and make the changes you need.
$str = 'type=showall&skip=20';
// this will parse the string and place the key/value pairs into $arr
parse_str($str,$arr);
// check if specific key exists
if (isset($arr['skip'])){
//if you need to know if it was there you can do stuff here
}
//set the newSkip value regardless
$arr['skip'] = $newSkip;
echo http_build_query($arr);
The http_build_query function will return the array into the same URI format that you started with. This function also encodes the final string so if you want to see the decoded version, you'll have to send it through urldecode().
References -
parse_str()
http_build_query()

Why do Multidimentional Arrays replace the first letter of the first key value?

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.

Categories