Beginner question - adding keys to existing array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Ben C
Forum Newbie
Posts: 7
Joined: Sat Mar 29, 2003 5:16 am

Beginner question - adding keys to existing array

Post 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 :)
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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;
Ben C
Forum Newbie
Posts: 7
Joined: Sat Mar 29, 2003 5:16 am

Post 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.
Ben C
Forum Newbie
Posts: 7
Joined: Sat Mar 29, 2003 5:16 am

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

because I forgot a ; after array() ;)
Post Reply