A
A
ant422021-12-08 21:23:14
PHP
ant42, 2021-12-08 21:23:14

How to display only certain elements of an array and ignore the rest?

I have an array of the form:

[Android=>link1, Windows=>link2, Mac=>link3, Linux=>link4, Default=>link2]

I display the elements from it with the command:

echo $auto_link[$osName];

$osName can be anything. But I want to display elements only for Mac and Linux, and for all other $osName, display an element with the Default key.

How to do it easier? In order not to alter the short entry "echo $auto_link[$osName];" and do not fence scripts with conditions. Maybe there is some kind of shorthand operator?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-12-08
@ant42

It's elementary

echo ($osName == 'Mac' || $osName == 'Linux') ? $auto_link[$osName] : $auto_link['Default'];

or
echo in_array($osName,['Mac', 'Linux']) ? $auto_link[$osName] : $auto_link['Default'];

PHP online test

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question