Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>foreach ($response as $object) { $basename = basename($object); $structure = explode("/", $object); echo $structure[0] . '&lt;br&gt;'; ... } </code></pre> <p>If you want to prevent duplicates in echo'ing out <code>$structure[0]</code>, you need to check whether you have had it already, e.g. by keeping a history:</p> <pre><code>$history = array(); foreach ($response as $object) { $name = strstr($object, "/", true); if ($name !== false &amp;&amp; !isset($history[$name])) { $history[$name] = 1; echo $name . '&lt;br&gt;'; } ... } </code></pre> <p>You probably want to stream line your code. Let's review:</p> <pre><code>foreach ($response as $object) { $basename = basename($object); $structure = explode("/", $object); echo $structure[0] . '&lt;br&gt;'; } </code></pre> <p>The line <code>$basename = basename($object);</code> is not used. It can be removed:</p> <pre><code>foreach ($response as $object) { $structure = explode("/", $object); echo $structure[0] . '&lt;br&gt;'; } </code></pre> <p>Then you only need the part of the string until the first <code>"/"</code>, the <code>strstr</code> function is handy for that:</p> <pre><code>foreach ($response as $object) { $part = strstr($object, "/", true); FALSE === $part &amp;&amp; $part = $object; echo $part . '&lt;br&gt;'; } </code></pre> <p>Now as we have already simplified it that much, we can create a simple mapping function:</p> <pre><code>$map = function($v) { $k = strstr($v, "/", true); FALSE === $k &amp;&amp; $k = $v; return $k; }; </code></pre> <p>and map the <code>$response</code>:</p> <pre><code>$mapped = array_map($map, $response); </code></pre> <p>and then unique it:</p> <pre><code>$unique = array_unique($mapped); </code></pre> <p>And job done. The code is much more easy to read:</p> <pre><code>$map = function($v) { $k = strstr($v, "/", true); FALSE === $k &amp;&amp; $k = $v; return $k; }; $mapped = array_map($map, $response); $unique = array_unique($mapped); foreach ($unique as $name) { echo $name, "&lt;br&gt;\n"; } </code></pre> <p>The additional benefit is here, in the moment you care about the output, the data to be outputted is already in order and properly available. As output itself counts as one part of your application, it should not be mixed with the data processing. See the <a href="http://en.wikipedia.org/wiki/IPO_Model" rel="nofollow">IPO Model</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload