Changing PHP array() elements

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
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Changing PHP array() elements

Post by mjseaden »

Hi

If I call substr() on a single variable, let's call it $var, then it seems to work. However, if I call the same substr() on an array element, for example, $array[0], then it doesn't change it. I also can't seem to set array elements with alternative values either.

Do I take it you can't alter elements of arrays in PHP?

Thanks

Mark
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

OK I am confused... substr does not change a variable, just returns what you want substring.

Code: Select all

$var='Hello There';
echo(substr($var,6);
$var=substr($var,0,5);
should set var $to 'Hello' after displaying 'There';

Code: Select all

$array=array('Hello There', 'How you doing');
$array[0]=substr($array[0],0,5);
should change the first element of the array to 'Hello';

Code: Select all

$array=array('Hello There', 'How you doing');
foreach ($array as $key=>$value) {
  $array[$key]=strtoupper($value);
}
Converts all of array to uppercase.

If you have a specific example of the problem (php code) it would be useful.
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Re: Changing PHP array() elements

Post by patrikG »

mjseaden wrote:Hi

If I call substr() on a single variable, let's call it $var, then it seems to work. However, if I call the same substr() on an array element, for example, $array[0], then it doesn't change it. I also can't seem to set array elements with alternative values either.

Do I take it you can't alter elements of arrays in PHP?

Thanks

Mark
subst() is a function for strings. Arrays a different type of variable. See http://uk.php.net/manual/en/language.types.php
Post Reply