Create array index only if data is set

Hi guys,

Check out the following code:

$element = explode("*", $this->session->data['tariff_cart'][$result['key']]);  // iexplode data1*data2* etc into different parts
$element = explode("*", "1*1*1*1*1*1*1*1"); // so that you don't get undefined offset

        		$this->data['products'][] = array(
          			'key'      => $result['key'],
          			'network'   => $element[0],
          			'plan'   => $element[1],
          			'tariff_length'   => $element[2],
          			'minutes'   => $element[3],
          			'texts'   => $element[4],
          			'data'   => $element[5],
          			'price'   => $element[6],
           			'name'     => $result['name'],
          			'model'    => $result['model'],

So basically I am making a mod to an e-commerce cms so that it reads data1data2data3* etc etc out of a db, explodes it into different parts and then populates the array above with those parts.

However, on some occasions there will be no data so I have the else condition which just fills it with meaningless data , in this case 1s in order to prevent the error which says : undefined offset 2 in array blah blah.

So here’s my question, I know that when a variable isn’t set you can check by using isset() or !== NULL and things like that to prevent errors but what about when populating an array in this manner could I do something like:

		$this->data['products'][] = array(
          			'key'      => $result['key'],
          			'network'   => isset($element[0]),

I know that this is ridiculous syntax and doesn’t work but what is the correct php equivalent or have I already done all that could be done in this situation?

It looks like you’re trying to declare a Ternary.
‘network’ => (isset($element[0]) ? $element[0] : “”)

Element ‘network’ = (Question: Does $element[0] exist? If yes, use element[0]. Else use the empty string.)

NOTE: element[0] will always exist if you explode on something, even if it’s an empty string or nonexistant variable. (doing it on a non-existant will throw an E_NOTICE level warning though.)

Ah that’s great thanks starlion!

I am aware of the ternary operator but now that I know I can use it in an array declaration I shall use it more often. :wink: