Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

General PHP

Featured Replies

So I got this idea from the threads general JavaScript and General CSS so this is General PHP. Feel free to post PHP snippets that others may find helpful. I will start...

 

Remove From Array By Value

 

Simply removes a given element from an array by its value

<?php

function removeFromArrayByValue($array,$valToRemove)
{
 if(!is_array($array))
{
return;
}

$newArray = array_diff($array,array($valToRemove));

return $newArray;

}

Usage

<?php

$arrayMinusVal = removeFromArrayByValue(array("red","green","blue","orange"),"blue");

//Will output red,green,orange... blue is removed
foreach($arrayMinusVal as $newVals):
echo $newVals."<br />";
endforeach;

Edited by webdesigner93

The function above could be extended to handle all sorts of array operations it might be useful for some to have a universal array-handler function

Remove, add, sort and shuffle

<?php
function processArray($array, $operation, $value=NULL) {
    if (!is_array($array)){
        return;
    }
    if (!isset($operation)){
        return;
    }
    if ($operation == "remove" && isset($value)){
        $newArray = array_diff($array, array($value));
    }
    elseif ($operation == "add" && isset($value)){
        array_push($array, $value);
        $newArray = $array;
    }
    elseif ($operation == "sort"){
        asort($array);
        $newArray = $array;
    }
    elseif ($operation == "shuffle"){
        shuffle($array);
        $newArray = $array;
    }
    /*More elseifs here for other array operations*/
    else{
        return;
    }
    return $newArray;
}

Usage

Some of the examples needs 3 arguments the array [array], the operation[string] and the value[string])
others only the array and the operation

<?php
$processedArray = processArray(array("red","green","blue","orange"), "remove", "blue");
//Will output red,green,orange... blue is removed
foreach($processedArray as $newVals):
echo $newVals."<br />";
endforeach;

$processedArray = processArray(array("red","green","blue","orange"), "add", "purple");
//Will output red,green,blue,orange,purple... purple is added
foreach($processedArray as $newVals):
echo $newVals."<br />";
endforeach;

$processedArray = processArray(array("red","green","blue","orange"), "sort");
//Will output the values alphabetically: "blue","green","orange","red"
foreach($processedArray as $newVals):
echo $newVals."<br />";
endforeach;

$processedArray = processArray(array("red","green","blue","orange"), "shuffle");
//Will output the values in random order
foreach($processedArray as $newVals):
echo $newVals."<br />";
endforeach;

Edited by Nillervision

  • Author

 

The function above could be extended to handle all sorts of array operations it might be useful for some to have a universal array-handler function

 

Remove, add, sort and shuffle

<?php
function processArray($array, $operation, $value=NULL) {
    if (!is_array($array)){
        return;
    }
    if (!isset($operation)){
        return;
    }
    if ($operation == "remove" && isset($value)){
        $newArray = array_diff($array, array($value));
    }
    elseif ($operation == "add" && isset($value)){
        array_push($array, $value);
        $newArray = $array;
    }
    elseif ($operation == "sort"){
        asort($array);
        $newArray = $array;
    }
    elseif ($operation == "shuffle"){
        shuffle($array);
        $newArray = $array;
    }
    /*More elseifs here for other array operations*/
    else{
        return;
    }
    return $newArray;
}

 

 

 

Only change I would make

 

is to handle the operations using a switch statement

function processArray($array, $operation, $value=NULL) {
    if (!is_array($array)){
        return;
    }
    if (!isset($operation)){
        return;
    }

switch($operation):
   case 'remove':
   if(!isset($value)){
       break;
   }
   $newArray = array_diff($array, array($value));
   break;
    case 'add':
   if(!isset($value)){
       break;
   }
    array_push($array, $value);
    $newArray = $array;
   break;
    case 'sort':
   asort($array);
   $newArray = $array;
   break;
    case 'shuffle':
   shuffle($array);
   $newArray = $array;
   break;
   endswitch;

   return $newArray;
}

Edited by webdesigner93

A nicer way of doing this would be to split each one of these operations out to a single function, or a bunch of methods on a class, that way you can call multiple methods on a single collection of data. Switch and multiple conditional statements will get messy real quick, it won't take long for this code to out of hand, and you can't easily require it into other parts of your app to use again.

Here's an example using the Knapsack package, Laravel has something similar called Collections.

<?php

require_once 'vendor/autoload.php';
use DusanKasan\Knapsack\Collection;

$collection = Collection::from(['red', 'green', 'blue', 'orange'])
  ->append('purple')
  ->filter(function($item){
    return $item !== 'orange';
  })
  ->printDump()
  ->toArray(); //array ( 0 => 'red', 1 => 'green', 2 => 'blue', 4 => 'purple', )

?>

You can easily chain these methods together to get the right data set back out, without any loops or conditionals. It's a lot more obvious what's going on at a given point in time IMO.

Edited by Jack

This is much nicer!

 

It would be nicer still if PHP had arrow functions and implicit return like JS.

 

---

 

To do the first example posted by webdesigner93, all that's required is filter.

$collection = Collection::from(['red', 'green', 'blue', 'orange'])
  ->filter(function($item){
    return $item !== 'blue';
  })
  ->toArray();

This should feel pretty natural to anyone that has used array methods before in JS. The example above can be written as:

const coloursCollection = ['red', 'green', 'blue', 'orange']
  .filter(item => item !== 'blue');

Although, the array would be better assigned to its own separate variable ¯\_(ツ)_/¯

 

If anyone's curious about this approach in PHP, I recommend taking 10 mins to watch this https://vimeo.com/115719437.

 

It would be nicer still if PHP had arrow functions and implicit return like JS.

 

---

 

To do the first example posted by webdesigner93, all that's required is filter.

$collection = Collection::from(['red', 'green', 'blue', 'orange'])
  ->filter(function($item){
    return $item !== 'blue';
  })
  ->toArray();

This should feel pretty natural to anyone that has used array methods before in JS. The example above can be written as:

const coloursCollection = ['red', 'green', 'blue', 'orange']
  .filter(item => item !== 'blue');

Although, the array would be better assigned to its own separate variable ¯\_(ツ)_/¯

 

If anyone's curious about this approach in PHP, I recommend taking 10 mins to watch this https://vimeo.com/115719437.

Just use JS you then get asynchronous flow out of the box which is lovely with async/await :)

 

Uncle Bob would be proud of that code Jack, that's much cleaner! Functional programming for the win ;)

 

The nice thing this can be further abstracted and made into a re-usable utility to handle all kinds of collections. Functional programming allows you to compose generic functions together in all kinds of interesting ways, I'm amazed it's only recently getting traction as the concepts and supporting languages (Lisp) have been around for nearly half a century.

const filterIn = (x, y) => x === y
const filterOut = (x, y) => x !== y
const filterBy = (collection, fn, prop) => collection.filter(i => fn(i, prop))


const coloursCollection = ['red', 'green', 'blue', 'orange',]

const redItems = filterBy(coloursCollection, filterIn, 'red')
const notBlueItems = filterBy(coloursCollection, filterOut, 'blue')

The code above might look verbose but when you start using the generic functions across a large codebase things become much more terse, you will have reduced bugs as these utilities can be very easily tested and relied upon.

Edited by rbrtsmith

Another bonus is that pure functions can also be memoized. Which is of great benefit if that function is called many times in quick succession, does heavy computation or both.

Because a pure function will return the same result given the same arguments consistently it can be memoized - which means if it's called with some given arguments it will store the result, so if it's called again with those exact arguments it can just return the stored result instead of re-doing the computation.

 

Reselect https://github.com/reactjs/reselect is a library we really heavily use in work, we use Redux which is an application state management package. What Reselect does is allow us to memoize derived data - data that is the result of selecting some state from the Redux store and transforming it in some way. We have a huge amount of state in our application so this memoization makes a very noticeable difference in performance.
None of this would be possible if the functions were not pure.

Edited by rbrtsmith

const filterIn = (x, y) => x === y
const filterOut = (x, y) => x !== y

Could also be written more generically:

const equal = (x, y) => x === y
const notEqual = (x, y) => x !== y

That then can be used all over your application rather than just for filtering.

 

They're just levels of abstraction and they become re-useable utilities, which is the basis for a library such as Lodash.

I got a function I made for clean links / urls with parameters ...

function pageXtra($var) { if(trim($var)=="") { return "?"; } else { return "&"; } }; // Adds either a ? or a & for a url string.

... this lets you build up the extras on a link, handy for pagination and checking if pages should exist and what the URL should be vs the URL requested.

$url = "/mypage/";
$extras = "";
if(isset($_GET['page'])) {
$extras .= pageXtra($extras) . "page=" . (int)$_GET['page'];
}
if(isset($_GET['order'])) {
$extras .= pageXtra($extras) . "order=" . (int)$_GET['order'];
}

echo $url . $extras;

// Would be /mypage/?page=1 if page is set
// Would be /mypage/?order=1 if order is set
// Would be /mypage/?page=1&order=1 if both are set

Edited by BrowserBugs

  • 3 years later...
On 5/18/2017 at 6:28 AM, BrowserBugs said:

I got a function I made for clean links / urls with parameters ...


function pageXtra($var) { if(trim($var)=="") { return "?"; } else { return "&"; } }; // Adds either a ? or a & for a url string.

... this lets you build up the extras on a link, handy for pagination and checking if pages should exist and what the URL should be vs the URL requested.


$url = "/mypage/";
$extras = "";
if(isset($_GET['page'])) {
$extras .= pageXtra($extras) . "page=" . (int)$_GET['page'];
}
if(isset($_GET['order'])) {
$extras .= pageXtra($extras) . "order=" . (int)$_GET['order'];
}

echo $url . $extras;

// Would be /mypage/?page=1 if page is set
// Would be /mypage/?order=1 if order is set
// Would be /mypage/?page=1&order=1 if both are set

Hey BrowserBugs,
your function could be reduced to:
 

<?php

function pageXtra(string $value): bool 
{
	return (strpos($value, '?') === false) ? '?' : ini_get('arg_separator.input');
}

-Ursel

  • Jo 90 locked this topic
Guest
This topic is now closed to further replies.

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.