Main menu

15 minute php - Day 2

16 Jan
Published by Mark W. Breneman

Let's dive in a little deeper. I find it handy to know not only how to use the tools, but also the oddities and pit falls. Today we are going to take a deeper look at php index arrays.

 

How do you update a value in an array?

$foo = array('red',"blue","green");

$foo[0] = 'silver'; 

$foo[1] = 'white'; 

$foo[2] = 'purple'; 

 

What happens when you add an item to an index array and use a key beyond the current index range? How do you access it?

$foo = array('red',"blue","green");

$foo[31] = 'silver'; 

 

What happens when you use a nonnumeric value as the index key?

$foo = array('red',"blue","green");

$foo[bob] = 'silver'; 

 

What happens when you do this?

$foo = array('red',"blue","green");

$foo[3] = 'silver'; 

$foo[bob] = 'white'; 

$foo['bob jones'] = 'yellow';

$foo['03'] = 'black'; 

 

Note the space between the first name and last name. You must quote your key name if you use spaces. You don't have to quote single-word strings. For instance, $age['Fred'] is the same as $age[Fred]. However, it's considered good PHP style to always use quotes, because quoteless keys are indistinguishable from constants. 

 

 

 

What is the absolute shortest way to define and add an item to an array in php?

--- any guesses?

 

Answer:

$bar[]= 'ed';

Why does this work?

 

What is the shortest way to add an item to an existing array?

--- any guesses?

 

Answer:

$bar[]= 'mike';

 

 

How do you determine if an array is defined?

 

var_dump(isset($var1)); 

 

Vs

 

$var1[]='mark';

var_dump(isset($var1));

 

How to determine if a value is set in an array?

--- any guesses?

 

Answer:

$foo['bar'] = 'red';
var_dump(isset($foo['bar']));

 

We can also use array_key_exists.  

 

 

Every php book I have picked up makes a big deal about indexed arrays and associative arrays. I learned today that, PHP internally stores all arrays as associative arrays, so the only difference between associative and indexed arrays is what the keys happen to be. 

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.