PHP code example of actived / graphphp

1. Go to this page and download the library: Download actived/graphphp library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

actived / graphphp example snippets


use GraphPHP\Graph\Graph;
use GraphPHP\Node\Node;
use GraphPHP\Edge\Edge;

$graph = new Graph();

$nodeA = new Node('A');
$graph->addNode($nodeA);

$nodeB = new Node('B');
$edge = new Edge($nodeA, $nodeB);
$graph->addEdge($edge);

$graph->removeNode($nodeA);
$graph->removeEdge($edge);

$neighbors = $graph->getNeighbors($nodeB);

$matrix = $graph->getAdjacencyMatrix();

if ($graph->hasCycle()) {
    echo "The graph has a cycle.";
} else {
    echo "The graph does not have a cycle.";
}

$closure = $graph->transitiveClosure();

$pathInfo = $graph->shortestPathDijkstra($nodeA, $nodeC);
echo "Shortest path: " . implode(' -> ', $pathInfo['path']);
echo "Cost: " . $pathInfo['cost'];

echo $graph;

use GraphPHP\Graph\DiGraph;
use GraphPHP\Node\Node;
use GraphPHP\Edge\DirectedEdge;

$diGraph = new DiGraph();

$nodeA = new Node('A');
$nodeB = new Node('B');
$directedEdge = new DirectedEdge($nodeA, $nodeB);
$diGraph->addEdge($directedEdge);

$outgoingNeighbors = $diGraph->getNeighbors($nodeA);

$predecessors = $diGraph->getPredecessors($nodeB);

$pathInfo = $diGraph->shortestPathBellmanFord($nodeA, $nodeC);
echo "Shortest path: " . implode(' -> ', $pathInfo['path']);
echo "Cost: " . $pathInfo['cost'];

if ($diGraph->hasCycle()) {
    echo "The directed graph has a cycle.";
} else {
    echo "The directed graph does not have a cycle.";
}

$matrix = $diGraph->getAdjacencyMatrix();

use GraphPHP\Graph\DAG;
use GraphPHP\Node\Node;
use GraphPHP\Edge\DirectedEdge;

$graph = new DAG();
$nodeA = new Node('A');
$nodeB = new Node('B');
$nodeC = new Node('C');

$graph->addNode($nodeA)
    ->addNode($nodeB)
    ->addNode($nodeC)
    ->addEdge(new DirectedEdge($nodeA, $nodeB, 4))
    ->addEdge(new DirectedEdge($nodeB, $nodeC, -6))
    ->addEdge(new DirectedEdge($nodeA, $nodeC, 2));

$graph->transitiveReduction();
echo $graph; // Visual representation of the graph

$order = $graph->topologicalSort();
print_r($order);