Page 1 of 1

Beginner question - adding keys to existing array

Posted: Sat Mar 29, 2003 5:16 am
by Ben C
How can I add keys to an existing array without defining new values?

Code: Select all

<?php
$thebox = strtolower($_POST['thebox']);
// get form input into thebox and make it all lowercase

print "$thebox <hr>";
// prints the lowercase text to be counted, with horizontal line

$ascii_array = (count_chars($thebox));
// counts the characters in the text, and returns them in an array with ascii keys, 0 to 255

$count_array = array_slice ($ascii_array, 97, 26);
// slices out the lower case alphabet (a = 97) into a new array (a = 0)
?>
is what I have so far, and I need to change the keys of $count_array from 1,2...26 to a,b,c...z.

I know there'll be a simple answer, but please help, this is my first day with php.


Cheers!
-Ben :)

Posted: Sat Mar 29, 2003 6:16 am
by volka
changing the hashes? hm, I doubt there is a function for that (but there might be)

Code: Select all

$tmp = array()
foreach($count_array as $k=>$v)
	$tmp[ chr($k + 97) ] = $v;
$count_array = tmp;

Posted: Sat Mar 29, 2003 9:25 am
by Ben C
In the absence of a function, that's a very neat little workaround! :D

Three questions: I assume the final tmp should be $tmp ? And when, if ever, should the foreach commands be enclosed in curly braces? If they aren't, how does the parser know when the repeatable bit ends and the normal code starts?

Cheers.

Posted: Sat Mar 29, 2003 9:36 am
by Ben C
Hmm, it gives me a parse error:
unexpected T_FOREACH in I:\htdocs\count.php on line 41
where 41 is the foreach line.

Posted: Sat Mar 29, 2003 10:05 am
by volka
because I forgot a ; after array() ;)