Welcome to the MacNN Forums.

If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

You are here: MacNN Forums > Software - Troubleshooting and Discussion > Developer Center > Adding a key=>var to an existing array (PHP)

Adding a key=>var to an existing array (PHP)
Thread Tools
Grizzled Veteran
Join Date: Jun 2001
Status: Offline
Reply With Quote
Aug 14, 2004, 05:46 PM
 
In all the PHP documentation I've seen, they always create an array with items that have keys by doing $someArr = array('key'=>value ...), but how do you go about adding a key=>value item to an array after it's been created? I'm attempting to use the $someArr[] = $key=>$value format, but it errors on the =>. Any ideas? Here's the chunk of code I'm dealing with... (and the csv file)

[php]
<?php

// Open the CSV file
$handle = fopen("testset.csv", "r");

$row = 0;
$mainArray=array();
// Get each line, parse CSV, and create a 2D array of the data
while (($fields = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($fields);
for ($col=0; $col < $num; $col++)
{
$mainArray[$row][$col] = $fields[$col];
}

$row++;
}
fclose($handle);

// Make a new array for GROUP items
$groups=array();

// For each $array item...
foreach($mainArray as $v1)
{
// If the 0 field contains "GROUP"...
if($v1[0]=="GROUP")
{
// push key=>val into $groups[]
$groups[$v1[2]] = $v1[1];
// $v1[2] is a string, but PHP is trying to make it an integer
// to use for an index of $groups, not the key STRING I want. Both methods
// of typecasting have no effect.. (string)$v1[2] and strval($v1[2]).
// PHP does the string to integer conversion after they are called. How can I
// push a string 'key'=>value item into an array using $groups[] type syntax?
//
// I can concatenate a " " onto the end of the key and FORCE it to be a string...
// $groups[$v1[2]." "] = $v1[1];
// ...and use rtrim($key) whenever I need the key name, but that's awkward.
// Is there a better way to do this altogether, maybe?
}
}

//var_dump($groups);

$highof='016';

// Search for the value '016', and return the key if it exists
if(in_array($highof, $groups))
{
// only catching the first key...
// deal with this later with array_keys()
$key = rtrim(array_search($highof, $groups));
echo $key;
if(strlen($key)==3)
{
if($key{2}=="*")
echo " (special group)";
}
}
else
{
echo "Key <b>${highof}</b> not found.";
}

//$array1=array(1,2,3,4);
//$array2=array(4,6,7,8);

//print_r(array_merge($array1,$array2));

/*include_once("../php_functions/numberSeqence.php");

$seq=numberSeqence("even",1,21);
if($seq)
{
foreach($seq as $c)
{
echo $c." ";
}
}*/
?>
[/php]
     
Grizzled Veteran
Join Date: Jun 2001
Location: Melbourne, Australia
Status: Offline
Reply With Quote
Aug 14, 2004, 06:38 PM
 
You simply refer to the array by the key when you add a new element:-

Code:
<?php $array = ('australia' => 'gold', 'nz' => 'silver', 'canada' => 'bronze'); $array['usa'] = 'Did not finish'; ?>
Aussie, Aussie, Aussie. Oi! Oi! Oi!

Computer thez nohhh...
     
Grizzled Veteran
Join Date: Oct 2003
Status: Offline
Reply With Quote
Aug 14, 2004, 06:53 PM
 
add something to the beginning when building your array to force them to be string keys. otherwise anything that looks like a number will be treated as an interger.

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices.
     
Grizzled Veteran
Join Date: Jun 2001
Status: Offline
Reply With Quote
Aug 14, 2004, 07:51 PM
 
So do $groups[] = 'keyname' => 0; before adding the rest of the data? Or pad the key with a string?
     
Grizzled Veteran
Join Date: Oct 2003
Status: Offline
Reply With Quote
Aug 14, 2004, 08:27 PM
 
Originally posted by macgyvr64:
So do $groups[] = 'keyname' => 0; before adding the rest of the data? Or pad the key with a string?
you will have to pad the key with a string. since there is really only one array type in PHP (which can be integer or string, but they are the same array type), anything that looks like a number, like "88", will be interpreted as an interger.

In these cases, I just pad it with a string, like maybe pad it at the front with "key" so then it goes into the array as "key88" and therefore a string.
     
Grizzled Veteran
Join Date: Jun 2001
Location: Melbourne, Australia
Status: Offline
Reply With Quote
Aug 14, 2004, 09:43 PM
 
Originally posted by madmacgames:
you will have to pad the key with a string. since there is really only one array type in PHP (which can be integer or string, but they are the same array type), anything that looks like a number, like "88", will be interpreted as an interger.

In these cases, I just pad it with a string, like maybe pad it at the front with "key" so then it goes into the array as "key88" and therefore a string.
There's no problem really. If you know that you need a 'key' based array, then simply loop through it with a foreach rather than a numeric loop:-

[code]
<?php

$array = array();

$array[88] = 'value';

foreach ($array as $key => $value)
{
print "[$key] = $value<br />";
}

?>
Computer thez nohhh...
     
Grizzled Veteran
Join Date: Jun 2001
Status: Offline
Reply With Quote
Aug 14, 2004, 10:30 PM
 
My problem was that I wanted each key to be a string, instead of having mixed strings and indexes (like ["08"] and [88]). Not that it *really* matters, as I can get the key name since I'm searching the array by value and just returning the key...but it just isn't as "nice."
     
Grizzled Veteran
Join Date: Oct 2003
Status: Offline
Reply With Quote
Aug 14, 2004, 10:30 PM
 
Originally posted by Simon Mundy:
There's no problem really.
I think there could be some problems if you were trying to some things with it, like sorting it for example, and you were expecting all keys to strings, but some were integers.
     
Grizzled Veteran
Join Date: Jun 2001
Status: Offline
Reply With Quote
Aug 14, 2004, 10:56 PM
 
Originally posted by Simon Mundy:
You simply refer to the array by the key when you add a new element:-

Code:
<?php $array = ('australia' => 'gold', 'nz' => 'silver', 'canada' => 'bronze'); $array['usa'] = 'Did not finish'; ?>
Problem with this is that you're creating the array and filling it with data in the same shot. I want to be able to add a key => value to an array after it has been created. Also, you're specifying $array['usa'], but I only have $v[1] in my case, and PHP is interpreting it as an integer. I can't force it to be a string.
     
Grizzled Veteran
Join Date: Nov 2003
Location: Hebburn, UK
Status: Offline
Reply With Quote
Aug 15, 2004, 06:38 AM
 
Originally posted by macgyvr64:
Problem with this is that you're creating the array and filling it with data in the same shot. I want to be able to add a key => value to an array after it has been created.
Simon created and filled it in the same shot originally (with Australia, New Zealand and Canada), but adding the key=>value pair 'usa'=>'did not finish' is done after it's created...

Originally posted by macgyvr64:
Also, you're specifying $array['usa'], but I only have $v[1] in my case, and PHP is interpreting it as an integer. I can't force it to be a string.
That's because 1 is an integer. '1' is not, however (AFAIK).

Oh yeah - Come on Great Britain!!!
Just who are Britain? What do they? Who is them? And why?

Formerly Black Book
     
Grizzled Veteran
Join Date: Jun 2001
Status: Offline
Reply With Quote
Aug 15, 2004, 06:44 AM
 
Simon created and filled it in the same shot originally (with Australia, New Zealand and Canada), but adding the key=>value pair 'usa'=>'did not finish' is done after it's created...

I just got that, and my code's working :-P

That's because 1 is an integer. '1' is not, however (AFAIK).

In my case, I'm using [1] as an index for the array $v.
     
Grizzled Veteran
Join Date: Oct 2003
Status: Offline
Reply With Quote
Aug 15, 2004, 10:53 AM
 
Originally posted by Black Book:
That's because 1 is an integer. '1' is not, however (AFAIK).
actually that's not quite true. Because there is only one type of array in PHP, which can have integer and/or string keys, but the two are the same type of array and not different; therefore, anything you put in for a key that looks like a number is interpreted as an integer.

$array[1] and $array['1'] will both be interpreted as $array[1]

this little script below demontrates that:

[php]
<?php
$array = array('1' => 'value1',
'2' => 'value2',
'02' => 'value3',
'3' => 'value4');

echo "<pre>";
var_dump($array);
echo "</pre>";

// should echo 'value3' if all keys are in as strings.
// but instead echos 'value4' because anything looking
// like an integer is treaded like one in PHP array keys
echo $array[3];
?>
[/php]
     
   
Thread Tools
Forum Links
Forum Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Top
Privacy Policy
All times are GMT -5. The time now is 01:09 PM.
All contents of these forums © 1995-2011 MacNN. All rights reserved.
Branding + Design: www.gesamtbild.com
vBulletin v.3.8.7 © 2000-2011, Jelsoft Enterprises Ltd., Content Relevant URLs by vBSEO 3.3.2